adaptive-bitmask 1.0.0 → 2.0.4
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/README.md +220 -255
- package/dist/ai/index.d.mts +16 -1
- package/dist/ai/index.d.ts +16 -1
- package/dist/ai/index.js +102 -6
- package/dist/ai/index.mjs +53 -5
- package/dist/{chunk-ZWEXRT33.mjs → chunk-QICJNGMQ.mjs} +53 -2
- package/dist/cli/index.d.mts +1 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +378 -0
- package/dist/cli/index.mjs +355 -0
- package/dist/{coordinator-Df48t6yJ.d.mts → coordinator-CqBBHhXv.d.mts} +6 -1
- package/dist/{coordinator-Df48t6yJ.d.ts → coordinator-CqBBHhXv.d.ts} +6 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +53 -2
- package/dist/index.mjs +1 -1
- package/package.json +17 -4
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli/index.ts
|
|
4
|
+
import { intro, outro, text, select, confirm, spinner, isCancel, cancel } from "@clack/prompts";
|
|
5
|
+
import pc from "picocolors";
|
|
6
|
+
import fs from "fs";
|
|
7
|
+
import path from "path";
|
|
8
|
+
async function main() {
|
|
9
|
+
intro(`${pc.bgCyan(pc.black(" create-swarm "))} ${pc.dim("v1.0.0")}`);
|
|
10
|
+
const projectName = await text({
|
|
11
|
+
message: "What is your project name?",
|
|
12
|
+
placeholder: "my-agent-swarm",
|
|
13
|
+
validate(value) {
|
|
14
|
+
if (!value || value.length === 0) return "Value is required";
|
|
15
|
+
if (fs.existsSync(path.join(process.cwd(), value))) return "Directory already exists";
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
if (isCancel(projectName) || typeof projectName !== "string") {
|
|
19
|
+
cancel("Operation cancelled");
|
|
20
|
+
process.exit(0);
|
|
21
|
+
}
|
|
22
|
+
const intent = await text({
|
|
23
|
+
message: "What is your swarm's primary intent?",
|
|
24
|
+
placeholder: "algorithmic trading",
|
|
25
|
+
initialValue: "algorithmic trading"
|
|
26
|
+
});
|
|
27
|
+
if (isCancel(intent) || typeof intent !== "string") {
|
|
28
|
+
cancel("Operation cancelled");
|
|
29
|
+
process.exit(0);
|
|
30
|
+
}
|
|
31
|
+
const agentCount = await text({
|
|
32
|
+
message: "How many agents in the swarm?",
|
|
33
|
+
placeholder: "10",
|
|
34
|
+
initialValue: "10",
|
|
35
|
+
validate(value) {
|
|
36
|
+
if (!value) return "Value is required";
|
|
37
|
+
const num = parseInt(value);
|
|
38
|
+
if (isNaN(num) || num <= 0) return "Must be a positive number";
|
|
39
|
+
if (num > 1e3) return "Let's start smaller (< 1000)";
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
if (isCancel(agentCount) || typeof agentCount !== "string") {
|
|
43
|
+
cancel("Operation cancelled");
|
|
44
|
+
process.exit(0);
|
|
45
|
+
}
|
|
46
|
+
const useAiSdk = await confirm({
|
|
47
|
+
message: "Integrate with Vercel AI SDK (CoordinationSession + Middleware)?",
|
|
48
|
+
initialValue: true
|
|
49
|
+
});
|
|
50
|
+
if (isCancel(useAiSdk) || typeof useAiSdk !== "boolean") {
|
|
51
|
+
cancel("Operation cancelled");
|
|
52
|
+
process.exit(0);
|
|
53
|
+
}
|
|
54
|
+
const useDashboard = await confirm({
|
|
55
|
+
message: "Scaffold a Live Dashboard / Control Plane (WebSocket)?",
|
|
56
|
+
initialValue: true
|
|
57
|
+
});
|
|
58
|
+
if (isCancel(useDashboard) || typeof useDashboard !== "boolean") {
|
|
59
|
+
cancel("Operation cancelled");
|
|
60
|
+
process.exit(0);
|
|
61
|
+
}
|
|
62
|
+
const deployment = await select({
|
|
63
|
+
message: "Choose a deployment strategy:",
|
|
64
|
+
options: [
|
|
65
|
+
{ value: "cloud", label: "Cloud LLMs (OpenAI/Anthropic)", hint: "Fast, paid" },
|
|
66
|
+
{ value: "local", label: "Local Models (Ollama/Llama)", hint: "Private, free" },
|
|
67
|
+
{ value: "sim", label: "Simulation / Mock", hint: "Ultra-fast testing (no LLM latency)" }
|
|
68
|
+
]
|
|
69
|
+
});
|
|
70
|
+
if (isCancel(deployment) || typeof deployment !== "string") {
|
|
71
|
+
cancel("Operation cancelled");
|
|
72
|
+
process.exit(0);
|
|
73
|
+
}
|
|
74
|
+
const s = spinner();
|
|
75
|
+
s.start(`Scaffolding ${projectName}...`);
|
|
76
|
+
const projectPath = path.join(process.cwd(), projectName);
|
|
77
|
+
fs.mkdirSync(projectPath, { recursive: true });
|
|
78
|
+
const pkg = {
|
|
79
|
+
name: projectName,
|
|
80
|
+
version: "0.1.0",
|
|
81
|
+
type: "module",
|
|
82
|
+
scripts: {
|
|
83
|
+
start: "tsx index.ts",
|
|
84
|
+
dev: "tsx --watch index.ts"
|
|
85
|
+
},
|
|
86
|
+
dependencies: {
|
|
87
|
+
"adaptive-bitmask": "^1.0.0",
|
|
88
|
+
"dotenv": "^16.4.5",
|
|
89
|
+
"p-limit": "^5.0.0"
|
|
90
|
+
},
|
|
91
|
+
devDependencies: {
|
|
92
|
+
"typescript": "^5.4.0",
|
|
93
|
+
"tsx": "^4.10.0",
|
|
94
|
+
"@types/node": "^20.0.0"
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
if (useAiSdk) {
|
|
98
|
+
pkg.dependencies["ai"] = "^4.0.0";
|
|
99
|
+
pkg.dependencies["zod"] = "^3.23.0";
|
|
100
|
+
pkg.dependencies["@ai-sdk/openai"] = "latest";
|
|
101
|
+
}
|
|
102
|
+
if (useDashboard) {
|
|
103
|
+
pkg.dependencies["ws"] = "^8.17.0";
|
|
104
|
+
pkg.devDependencies["@types/ws"] = "^8.5.10";
|
|
105
|
+
}
|
|
106
|
+
fs.writeFileSync(path.join(projectPath, "package.json"), JSON.stringify(pkg, null, 2));
|
|
107
|
+
const tsconfig = {
|
|
108
|
+
compilerOptions: {
|
|
109
|
+
target: "ES2022",
|
|
110
|
+
module: "ESNext",
|
|
111
|
+
moduleResolution: "bundler",
|
|
112
|
+
strict: true,
|
|
113
|
+
esModuleInterop: true,
|
|
114
|
+
skipLibCheck: true
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
fs.writeFileSync(path.join(projectPath, "tsconfig.json"), JSON.stringify(tsconfig, null, 2));
|
|
118
|
+
const envContent = deployment === "cloud" ? "OPENAI_API_KEY=sk-your-key-here\n" : deployment === "local" ? "OLLAMA_BASE_URL=http://localhost:11434\n" : "";
|
|
119
|
+
fs.writeFileSync(path.join(projectPath, ".env"), envContent);
|
|
120
|
+
fs.writeFileSync(path.join(projectPath, ".gitignore"), "node_modules\n.env\ndist\n");
|
|
121
|
+
const indexTs = generateIndexTs({
|
|
122
|
+
projectName,
|
|
123
|
+
intent,
|
|
124
|
+
agentCount: parseInt(agentCount),
|
|
125
|
+
useAiSdk,
|
|
126
|
+
useDashboard,
|
|
127
|
+
deployment
|
|
128
|
+
});
|
|
129
|
+
fs.writeFileSync(path.join(projectPath, "index.ts"), indexTs);
|
|
130
|
+
s.stop(`Project ${projectName} scaffolded!`);
|
|
131
|
+
outro(`
|
|
132
|
+
${pc.green("Success!")} Your swarm is ready.
|
|
133
|
+
${useDashboard ? pc.blue("\u{1F5A5}\uFE0F Dashboard active at: http://localhost:3000") : ""}
|
|
134
|
+
|
|
135
|
+
${pc.dim("Next steps:")}
|
|
136
|
+
${pc.cyan(`cd ${projectName}`)}
|
|
137
|
+
${pc.cyan("npm install")}
|
|
138
|
+
${pc.cyan("npm start")}
|
|
139
|
+
|
|
140
|
+
${pc.yellow("Note:")} Edit ${pc.bold("index.ts")} to customize agent prompts and scoring.
|
|
141
|
+
`);
|
|
142
|
+
}
|
|
143
|
+
function generateIndexTs(config) {
|
|
144
|
+
const { intent, agentCount, useAiSdk, useDashboard, deployment } = config;
|
|
145
|
+
let imports = `import 'dotenv/config';
|
|
146
|
+
import { SharedCognition } from 'adaptive-bitmask';
|
|
147
|
+
import pLimit from 'p-limit';`;
|
|
148
|
+
if (useAiSdk) {
|
|
149
|
+
imports += `
|
|
150
|
+
import { CoordinationSession } from 'adaptive-bitmask/ai';
|
|
151
|
+
import { openai } from '@ai-sdk/openai';
|
|
152
|
+
import { generateText } from 'ai';`;
|
|
153
|
+
}
|
|
154
|
+
if (useDashboard) {
|
|
155
|
+
imports += `
|
|
156
|
+
import { WebSocketServer } from 'ws';
|
|
157
|
+
import { createServer } from 'http';`;
|
|
158
|
+
}
|
|
159
|
+
const concurrency = Math.min(agentCount, 10);
|
|
160
|
+
let dashboardCode = "";
|
|
161
|
+
if (useDashboard) {
|
|
162
|
+
dashboardCode = `
|
|
163
|
+
/**
|
|
164
|
+
* \u{1F5A5}\uFE0F DASHBOARD / CONTROL PLANE
|
|
165
|
+
* Real-time monitoring of agent "thinking", bandwidth, and coordination.
|
|
166
|
+
*/
|
|
167
|
+
const server = createServer((req, res) => {
|
|
168
|
+
res.writeHead(200, { 'Content-Type': 'text/html' });
|
|
169
|
+
res.end(\`
|
|
170
|
+
<html>
|
|
171
|
+
<head>
|
|
172
|
+
<title>Shared Cognition Dashboard</title>
|
|
173
|
+
<style>
|
|
174
|
+
body { font-family: system-ui; background: #0f172a; color: #f8fafc; margin: 0; padding: 2rem; }
|
|
175
|
+
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
|
|
176
|
+
.card { background: #1e293b; padding: 1.5rem; border-radius: 0.5rem; border: 1px solid #334155; }
|
|
177
|
+
.log { font-family: monospace; height: 300px; overflow-y: auto; background: #000; padding: 1rem; border-radius: 0.25rem; font-size: 0.8rem; }
|
|
178
|
+
.agent-thinking { color: #38bdf8; }
|
|
179
|
+
.decision { color: #4ade80; font-weight: bold; }
|
|
180
|
+
.feature { display: inline-block; background: #334155; padding: 0.2rem 0.5rem; border-radius: 1rem; margin-right: 0.5rem; font-size: 0.7rem; }
|
|
181
|
+
h1 { margin-top: 0; color: #e2e8f0; }
|
|
182
|
+
</style>
|
|
183
|
+
</head>
|
|
184
|
+
<body>
|
|
185
|
+
<h1>\u{1F9E0} Shared Cognition Dashboard</h1>
|
|
186
|
+
<div class="grid">
|
|
187
|
+
<div class="card">
|
|
188
|
+
<h2>Swarm Status</h2>
|
|
189
|
+
<div id="status">Waiting for round...</div>
|
|
190
|
+
<h3>Active Consensus Features</h3>
|
|
191
|
+
<div id="features"></div>
|
|
192
|
+
</div>
|
|
193
|
+
<div class="card">
|
|
194
|
+
<h2>Real-time Analytics</h2>
|
|
195
|
+
<p>Coordination Latency: <span id="latency">0</span>ms</p>
|
|
196
|
+
<p>Total Agents: ${agentCount}</p>
|
|
197
|
+
<p>Bandwidth Reduction: 85x (Bitmask Protocol)</p>
|
|
198
|
+
</div>
|
|
199
|
+
</div>
|
|
200
|
+
<div class="card" style="margin-top: 1rem;">
|
|
201
|
+
<h2>Live Agent Logs ("Thinking")</h2>
|
|
202
|
+
<div id="logs" class="log"></div>
|
|
203
|
+
</div>
|
|
204
|
+
<script>
|
|
205
|
+
const ws = new WebSocket('ws://localhost:3001');
|
|
206
|
+
const logEl = document.getElementById('logs');
|
|
207
|
+
const statusEl = document.getElementById('status');
|
|
208
|
+
const featuresEl = document.getElementById('features');
|
|
209
|
+
const latencyEl = document.getElementById('latency');
|
|
210
|
+
|
|
211
|
+
ws.onmessage = (event) => {
|
|
212
|
+
const data = JSON.parse(event.data);
|
|
213
|
+
if (data.type === 'log') {
|
|
214
|
+
const div = document.createElement('div');
|
|
215
|
+
const time = new Date(data.timestamp).toLocaleTimeString();
|
|
216
|
+
div.innerHTML = \\\`[\${time}] <b>\${data.agentId}:</b> \${data.content}\\\`;
|
|
217
|
+
if (data.logType === 'thinking') div.className = 'agent-thinking';
|
|
218
|
+
if (data.logType === 'decision') div.className = 'decision';
|
|
219
|
+
logEl.prepend(div);
|
|
220
|
+
} else if (data.type === 'update') {
|
|
221
|
+
statusEl.innerText = \\\`Round Complete: \${data.decision}\\\`;
|
|
222
|
+
featuresEl.innerHTML = data.features.map(f => \\\`<span class="feature">\${f}</span>\\\`).join('');
|
|
223
|
+
latencyEl.innerText = data.latency.toFixed(2);
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
</script>
|
|
227
|
+
</body>
|
|
228
|
+
</html>
|
|
229
|
+
\`);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
const wss = new WebSocketServer({ port: 3001 });
|
|
233
|
+
server.listen(3000);
|
|
234
|
+
|
|
235
|
+
function broadcast(data: any) {
|
|
236
|
+
const msg = JSON.stringify(data);
|
|
237
|
+
wss.clients.forEach(c => c.send(msg));
|
|
238
|
+
}
|
|
239
|
+
`;
|
|
240
|
+
}
|
|
241
|
+
const concurrencyLimit = Math.min(agentCount, 10);
|
|
242
|
+
let agentLogic = "";
|
|
243
|
+
if (deployment === "sim") {
|
|
244
|
+
agentLogic = `
|
|
245
|
+
/**
|
|
246
|
+
* SIMULATION MODE: Parallel Mock Agent Execution
|
|
247
|
+
*/
|
|
248
|
+
const mockFeatures = ['price_up', 'volume_spike', 'momentum_strong', 'breakout_detected', 'EMERGENCY_halt'];
|
|
249
|
+
|
|
250
|
+
async function runAgent(id: number${useAiSdk ? ", session: any" : ""}) {
|
|
251
|
+
const agentName = \`Agent-\${id}\`;
|
|
252
|
+
|
|
253
|
+
// Simulate "Thinking"
|
|
254
|
+
${useAiSdk ? `session.logThinking(agentName, 'Analyzing market indicators...');` : useDashboard ? `broadcast({ type: 'log', agentId: agentName, logType: 'thinking', content: 'Analyzing market indicators...', timestamp: Date.now() });` : ""}
|
|
255
|
+
|
|
256
|
+
await new Promise(r => setTimeout(r, 10 + Math.random() * 50));
|
|
257
|
+
|
|
258
|
+
const count = Math.floor(Math.random() * 3) + 1;
|
|
259
|
+
const features = [];
|
|
260
|
+
for(let i=0; i<count; i++) {
|
|
261
|
+
features.push(mockFeatures[Math.floor(Math.random() * mockFeatures.length)]);
|
|
262
|
+
}
|
|
263
|
+
return features;
|
|
264
|
+
}`;
|
|
265
|
+
} else if (useAiSdk) {
|
|
266
|
+
agentLogic = `
|
|
267
|
+
/**
|
|
268
|
+
* AI SDK MODE: Parallel LLM Execution
|
|
269
|
+
*/
|
|
270
|
+
async function runAgent(id: number, session: any) {
|
|
271
|
+
const agentName = \`Agent-\${id}\`;
|
|
272
|
+
session.logThinking(agentName, 'Prompting LLM for observation...');
|
|
273
|
+
|
|
274
|
+
const { text } = await generateText({
|
|
275
|
+
model: openai('gpt-4o-mini'),
|
|
276
|
+
system: \`You are a \${intent} agent. Analyze the situation and output 1-3 relevant features from the schema as comma-separated strings.\`,
|
|
277
|
+
prompt: 'Current state analysis...',
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
const features = text.split(',').map(f => f.trim());
|
|
281
|
+
return features;
|
|
282
|
+
}`;
|
|
283
|
+
} else {
|
|
284
|
+
agentLogic = `
|
|
285
|
+
/**
|
|
286
|
+
* BASIC MODE: Parallel fetch execution
|
|
287
|
+
*/
|
|
288
|
+
async function runAgent(id: number) {
|
|
289
|
+
const agentName = \`Agent-\${id}\`;
|
|
290
|
+
${useDashboard ? `broadcast({ type: 'log', agentId: agentName, logType: 'thinking', content: 'Fetching data...', timestamp: Date.now() });` : ""}
|
|
291
|
+
return ['feature_a', 'feature_b'];
|
|
292
|
+
}`;
|
|
293
|
+
}
|
|
294
|
+
return `${imports}
|
|
295
|
+
|
|
296
|
+
const intent = "${intent}";
|
|
297
|
+
const agentCount = ${agentCount};
|
|
298
|
+
const limit = pLimit(${concurrencyLimit});
|
|
299
|
+
|
|
300
|
+
${dashboardCode}
|
|
301
|
+
|
|
302
|
+
${useAiSdk ? `const session = new CoordinationSession({
|
|
303
|
+
features: ['price_up', 'volume_spike', 'trend_up', 'volatility_high'],
|
|
304
|
+
onLog: (log) => {
|
|
305
|
+
${useDashboard ? "broadcast({ type: 'log', agentId: log.agentId, logType: log.type, content: log.content, timestamp: log.timestamp });" : "console.log(`[${new Date(log.timestamp).toLocaleTimeString()}] ${log.agentId}: ${log.content}`);"}
|
|
306
|
+
}
|
|
307
|
+
});` : `const cognition = new SharedCognition();`}
|
|
308
|
+
|
|
309
|
+
${agentLogic}
|
|
310
|
+
|
|
311
|
+
async function runSwarm() {
|
|
312
|
+
console.log(\`\u{1F680} Starting swarm: "\${intent}" with \${agentCount} agents...\`);
|
|
313
|
+
|
|
314
|
+
while (true) {
|
|
315
|
+
const start = performance.now();
|
|
316
|
+
${useAiSdk ? "session.startRound();" : ""}
|
|
317
|
+
|
|
318
|
+
const agentTasks = Array.from({ length: agentCount }, (_, i) =>
|
|
319
|
+
limit(() => runAgent(i${useAiSdk ? ", session" : ""}))
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
const allObservations = await Promise.all(agentTasks);
|
|
323
|
+
const llmTime = performance.now() - start;
|
|
324
|
+
|
|
325
|
+
const coordStart = performance.now();
|
|
326
|
+
${useAiSdk ? `
|
|
327
|
+
allObservations.forEach((obs, i) => session.report(\`agent-\${i}\`, obs));
|
|
328
|
+
const { decision, result, aggregatedFeatures } = session.decide();
|
|
329
|
+
const finalScore = result.finalScore;
|
|
330
|
+
` : `
|
|
331
|
+
const { decision, finalScore, activeFeatures: aggregatedFeatures } = cognition.processSwarmTick(allObservations);
|
|
332
|
+
`}
|
|
333
|
+
const coordTime = performance.now() - coordStart;
|
|
334
|
+
|
|
335
|
+
${useDashboard ? `
|
|
336
|
+
broadcast({
|
|
337
|
+
type: 'update',
|
|
338
|
+
decision,
|
|
339
|
+
features: aggregatedFeatures,
|
|
340
|
+
latency: coordTime,
|
|
341
|
+
totalLatency: performance.now() - start
|
|
342
|
+
});
|
|
343
|
+
` : ""}
|
|
344
|
+
|
|
345
|
+
console.log(\`\\nDecision: \${decision} (Coord: \${coordTime.toFixed(2)}ms, Total: \${(performance.now() - start).toFixed(2)}ms)\`);
|
|
346
|
+
|
|
347
|
+
// Pause between ticks
|
|
348
|
+
await new Promise(r => setTimeout(r, 2000));
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
runSwarm().catch(console.error);
|
|
353
|
+
`;
|
|
354
|
+
}
|
|
355
|
+
main().catch(console.error);
|
|
@@ -510,6 +510,11 @@ declare class Coordinator {
|
|
|
510
510
|
* Returns number of messages accepted.
|
|
511
511
|
*/
|
|
512
512
|
receiveAll(messages: BitmaskMessage[]): number;
|
|
513
|
+
/**
|
|
514
|
+
* Peek at current consensus state without clearing the buffer.
|
|
515
|
+
* Useful for mid-round status queries by AI agents.
|
|
516
|
+
*/
|
|
517
|
+
peekAggregate(): AggregationResult;
|
|
513
518
|
/**
|
|
514
519
|
* Aggregate all buffered messages into a consensus result.
|
|
515
520
|
* Clears the buffer after aggregation.
|
|
@@ -518,4 +523,4 @@ declare class Coordinator {
|
|
|
518
523
|
private _emitTelemetry;
|
|
519
524
|
}
|
|
520
525
|
|
|
521
|
-
export { Arbiter as A, BitmaskMessage as B, Coordinator as C, type Decision as D, EMERGENCY_RANGE as E, delta as F, emergencyBits as G, HIGH_FREQ_RANGE as H, empty as I, encode as J, forEachSetBit as K, fromBytes as L, MED_FREQ_RANGE as M, hammingDistance as N, hasEmergency as O, type PruneResult as P, intersect as Q, merge as R, SchemaManager as S, popcount as T, setBit as U, testBit as V, toBytes as W, type
|
|
526
|
+
export { Arbiter as A, BitmaskMessage as B, Coordinator as C, type Decision as D, EMERGENCY_RANGE as E, delta as F, emergencyBits as G, HIGH_FREQ_RANGE as H, empty as I, encode as J, forEachSetBit as K, fromBytes as L, MED_FREQ_RANGE as M, hammingDistance as N, hasEmergency as O, type PruneResult as P, intersect as Q, merge as R, SchemaManager as S, popcount as T, setBit as U, testBit as V, toBytes as W, type CoordinatorConfig as a, type ArbiterConfig as b, type ArbiterResult as c, type SchemaConfig as d, type AggregationResult as e, type ArbiterTelemetryEvent as f, BITMASK_WIDTH as g, type BitConfidence as h, type Bitmask as i, type BitmaskMessageData as j, type CoordinatorDropReason as k, type CoordinatorTelemetryEvent as l, type EncodeOptions as m, type ExportedSchema as n, MESSAGE_SIZE_BYTES as o, type SchemaSnapshot as p, type ScoreStrategiesOptions as q, type StaleMessagePolicy as r, type StrategyCandidate as s, type StrategyDecisionResult as t, type StrategyScore as u, activeBits as v, clearBit as w, createFinancialArbiter as x, createRoboticArbiter as y, decode as z };
|
|
@@ -510,6 +510,11 @@ declare class Coordinator {
|
|
|
510
510
|
* Returns number of messages accepted.
|
|
511
511
|
*/
|
|
512
512
|
receiveAll(messages: BitmaskMessage[]): number;
|
|
513
|
+
/**
|
|
514
|
+
* Peek at current consensus state without clearing the buffer.
|
|
515
|
+
* Useful for mid-round status queries by AI agents.
|
|
516
|
+
*/
|
|
517
|
+
peekAggregate(): AggregationResult;
|
|
513
518
|
/**
|
|
514
519
|
* Aggregate all buffered messages into a consensus result.
|
|
515
520
|
* Clears the buffer after aggregation.
|
|
@@ -518,4 +523,4 @@ declare class Coordinator {
|
|
|
518
523
|
private _emitTelemetry;
|
|
519
524
|
}
|
|
520
525
|
|
|
521
|
-
export { Arbiter as A, BitmaskMessage as B, Coordinator as C, type Decision as D, EMERGENCY_RANGE as E, delta as F, emergencyBits as G, HIGH_FREQ_RANGE as H, empty as I, encode as J, forEachSetBit as K, fromBytes as L, MED_FREQ_RANGE as M, hammingDistance as N, hasEmergency as O, type PruneResult as P, intersect as Q, merge as R, SchemaManager as S, popcount as T, setBit as U, testBit as V, toBytes as W, type
|
|
526
|
+
export { Arbiter as A, BitmaskMessage as B, Coordinator as C, type Decision as D, EMERGENCY_RANGE as E, delta as F, emergencyBits as G, HIGH_FREQ_RANGE as H, empty as I, encode as J, forEachSetBit as K, fromBytes as L, MED_FREQ_RANGE as M, hammingDistance as N, hasEmergency as O, type PruneResult as P, intersect as Q, merge as R, SchemaManager as S, popcount as T, setBit as U, testBit as V, toBytes as W, type CoordinatorConfig as a, type ArbiterConfig as b, type ArbiterResult as c, type SchemaConfig as d, type AggregationResult as e, type ArbiterTelemetryEvent as f, BITMASK_WIDTH as g, type BitConfidence as h, type Bitmask as i, type BitmaskMessageData as j, type CoordinatorDropReason as k, type CoordinatorTelemetryEvent as l, type EncodeOptions as m, type ExportedSchema as n, MESSAGE_SIZE_BYTES as o, type SchemaSnapshot as p, type ScoreStrategiesOptions as q, type StaleMessagePolicy as r, type StrategyCandidate as s, type StrategyDecisionResult as t, type StrategyScore as u, activeBits as v, clearBit as w, createFinancialArbiter as x, createRoboticArbiter as y, decode as z };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { WebSocket } from 'ws';
|
|
2
|
-
import { S as SchemaManager, C as Coordinator, A as Arbiter,
|
|
3
|
-
export { e as AggregationResult, f as ArbiterTelemetryEvent, g as BITMASK_WIDTH, h as BitConfidence, i as Bitmask, j as BitmaskMessageData, k as CoordinatorDropReason, l as CoordinatorTelemetryEvent, D as Decision, E as EMERGENCY_RANGE, m as EncodeOptions, n as ExportedSchema, H as HIGH_FREQ_RANGE, M as MED_FREQ_RANGE, o as MESSAGE_SIZE_BYTES, P as PruneResult, p as SchemaSnapshot, q as ScoreStrategiesOptions, r as StaleMessagePolicy, s as StrategyCandidate, t as StrategyDecisionResult, u as StrategyScore, v as activeBits, w as clearBit, x as createFinancialArbiter, y as createRoboticArbiter, z as decode, F as delta, G as emergencyBits, I as empty, J as encode, K as forEachSetBit, L as fromBytes, N as hammingDistance, O as hasEmergency, Q as intersect, R as merge, T as popcount, U as setBit, V as testBit, W as toBytes } from './coordinator-
|
|
2
|
+
import { S as SchemaManager, C as Coordinator, A as Arbiter, d as SchemaConfig, a as CoordinatorConfig, b as ArbiterConfig, c as ArbiterResult, B as BitmaskMessage } from './coordinator-CqBBHhXv.mjs';
|
|
3
|
+
export { e as AggregationResult, f as ArbiterTelemetryEvent, g as BITMASK_WIDTH, h as BitConfidence, i as Bitmask, j as BitmaskMessageData, k as CoordinatorDropReason, l as CoordinatorTelemetryEvent, D as Decision, E as EMERGENCY_RANGE, m as EncodeOptions, n as ExportedSchema, H as HIGH_FREQ_RANGE, M as MED_FREQ_RANGE, o as MESSAGE_SIZE_BYTES, P as PruneResult, p as SchemaSnapshot, q as ScoreStrategiesOptions, r as StaleMessagePolicy, s as StrategyCandidate, t as StrategyDecisionResult, u as StrategyScore, v as activeBits, w as clearBit, x as createFinancialArbiter, y as createRoboticArbiter, z as decode, F as delta, G as emergencyBits, I as empty, J as encode, K as forEachSetBit, L as fromBytes, N as hammingDistance, O as hasEmergency, Q as intersect, R as merge, T as popcount, U as setBit, V as testBit, W as toBytes } from './coordinator-CqBBHhXv.mjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* WebSocket transport layer for adaptive-bitmask
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { WebSocket } from 'ws';
|
|
2
|
-
import { S as SchemaManager, C as Coordinator, A as Arbiter,
|
|
3
|
-
export { e as AggregationResult, f as ArbiterTelemetryEvent, g as BITMASK_WIDTH, h as BitConfidence, i as Bitmask, j as BitmaskMessageData, k as CoordinatorDropReason, l as CoordinatorTelemetryEvent, D as Decision, E as EMERGENCY_RANGE, m as EncodeOptions, n as ExportedSchema, H as HIGH_FREQ_RANGE, M as MED_FREQ_RANGE, o as MESSAGE_SIZE_BYTES, P as PruneResult, p as SchemaSnapshot, q as ScoreStrategiesOptions, r as StaleMessagePolicy, s as StrategyCandidate, t as StrategyDecisionResult, u as StrategyScore, v as activeBits, w as clearBit, x as createFinancialArbiter, y as createRoboticArbiter, z as decode, F as delta, G as emergencyBits, I as empty, J as encode, K as forEachSetBit, L as fromBytes, N as hammingDistance, O as hasEmergency, Q as intersect, R as merge, T as popcount, U as setBit, V as testBit, W as toBytes } from './coordinator-
|
|
2
|
+
import { S as SchemaManager, C as Coordinator, A as Arbiter, d as SchemaConfig, a as CoordinatorConfig, b as ArbiterConfig, c as ArbiterResult, B as BitmaskMessage } from './coordinator-CqBBHhXv.js';
|
|
3
|
+
export { e as AggregationResult, f as ArbiterTelemetryEvent, g as BITMASK_WIDTH, h as BitConfidence, i as Bitmask, j as BitmaskMessageData, k as CoordinatorDropReason, l as CoordinatorTelemetryEvent, D as Decision, E as EMERGENCY_RANGE, m as EncodeOptions, n as ExportedSchema, H as HIGH_FREQ_RANGE, M as MED_FREQ_RANGE, o as MESSAGE_SIZE_BYTES, P as PruneResult, p as SchemaSnapshot, q as ScoreStrategiesOptions, r as StaleMessagePolicy, s as StrategyCandidate, t as StrategyDecisionResult, u as StrategyScore, v as activeBits, w as clearBit, x as createFinancialArbiter, y as createRoboticArbiter, z as decode, F as delta, G as emergencyBits, I as empty, J as encode, K as forEachSetBit, L as fromBytes, N as hammingDistance, O as hasEmergency, Q as intersect, R as merge, T as popcount, U as setBit, V as testBit, W as toBytes } from './coordinator-CqBBHhXv.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* WebSocket transport layer for adaptive-bitmask
|
package/dist/index.js
CHANGED
|
@@ -2010,6 +2010,52 @@ var Coordinator = class {
|
|
|
2010
2010
|
}
|
|
2011
2011
|
return accepted;
|
|
2012
2012
|
}
|
|
2013
|
+
/**
|
|
2014
|
+
* Peek at current consensus state without clearing the buffer.
|
|
2015
|
+
* Useful for mid-round status queries by AI agents.
|
|
2016
|
+
*/
|
|
2017
|
+
peekAggregate() {
|
|
2018
|
+
if (this._buffer.length === 0) {
|
|
2019
|
+
return {
|
|
2020
|
+
aggregatedMask: 0n,
|
|
2021
|
+
confidence: /* @__PURE__ */ new Map(),
|
|
2022
|
+
messageCount: 0,
|
|
2023
|
+
uniqueAgents: 0,
|
|
2024
|
+
staleMessages: 0,
|
|
2025
|
+
droppedStaleMessages: this._droppedStaleMessages,
|
|
2026
|
+
aggregationTimeUs: 0
|
|
2027
|
+
};
|
|
2028
|
+
}
|
|
2029
|
+
const t0 = performance.now();
|
|
2030
|
+
let aggregated = 0n;
|
|
2031
|
+
const bitVotes = /* @__PURE__ */ new Map();
|
|
2032
|
+
const uniqueAgents = /* @__PURE__ */ new Set();
|
|
2033
|
+
let staleCount = 0;
|
|
2034
|
+
for (const msg of this._buffer) {
|
|
2035
|
+
uniqueAgents.add(msg.agentId);
|
|
2036
|
+
if (this._schemaVersion !== void 0 && msg.schemaVersion !== this._schemaVersion) {
|
|
2037
|
+
staleCount++;
|
|
2038
|
+
}
|
|
2039
|
+
aggregated |= msg.mask;
|
|
2040
|
+
forEachSetBit(msg.mask, (bit) => {
|
|
2041
|
+
bitVotes.set(bit, (bitVotes.get(bit) ?? 0) + 1);
|
|
2042
|
+
});
|
|
2043
|
+
}
|
|
2044
|
+
const confidence = /* @__PURE__ */ new Map();
|
|
2045
|
+
for (const [bit, count] of bitVotes) {
|
|
2046
|
+
confidence.set(bit, count / this._buffer.length);
|
|
2047
|
+
}
|
|
2048
|
+
const elapsed = (performance.now() - t0) * 1e3;
|
|
2049
|
+
return {
|
|
2050
|
+
aggregatedMask: aggregated,
|
|
2051
|
+
confidence,
|
|
2052
|
+
messageCount: this._buffer.length,
|
|
2053
|
+
uniqueAgents: uniqueAgents.size,
|
|
2054
|
+
staleMessages: staleCount,
|
|
2055
|
+
droppedStaleMessages: this._droppedStaleMessages,
|
|
2056
|
+
aggregationTimeUs: elapsed
|
|
2057
|
+
};
|
|
2058
|
+
}
|
|
2013
2059
|
/**
|
|
2014
2060
|
* Aggregate all buffered messages into a consensus result.
|
|
2015
2061
|
* Clears the buffer after aggregation.
|
|
@@ -2037,8 +2083,6 @@ var Coordinator = class {
|
|
|
2037
2083
|
}
|
|
2038
2084
|
const elapsed = (performance.now() - t0) * 1e3;
|
|
2039
2085
|
this._aggregationCount++;
|
|
2040
|
-
this._buffer = [];
|
|
2041
|
-
this._seenAgents.clear();
|
|
2042
2086
|
const result = {
|
|
2043
2087
|
aggregatedMask: aggregated,
|
|
2044
2088
|
confidence,
|
|
@@ -2048,6 +2092,10 @@ var Coordinator = class {
|
|
|
2048
2092
|
droppedStaleMessages: this._droppedStaleMessages,
|
|
2049
2093
|
aggregationTimeUs: elapsed
|
|
2050
2094
|
};
|
|
2095
|
+
this._buffer = [];
|
|
2096
|
+
this._seenAgents.clear();
|
|
2097
|
+
this._roundStartTime = 0;
|
|
2098
|
+
this._droppedStaleMessages = 0;
|
|
2051
2099
|
this._emitTelemetry({ type: "round_aggregated", result });
|
|
2052
2100
|
return result;
|
|
2053
2101
|
}
|
|
@@ -2366,6 +2414,9 @@ var SharedCognition = class {
|
|
|
2366
2414
|
*/
|
|
2367
2415
|
processSwarmTick(agentObservations) {
|
|
2368
2416
|
const startMs = performance.now();
|
|
2417
|
+
if (this.schema.activeFeatureCount >= 50) {
|
|
2418
|
+
this.schema.prune();
|
|
2419
|
+
}
|
|
2369
2420
|
if (this.autoRegister) {
|
|
2370
2421
|
const uniqueFeatures = /* @__PURE__ */ new Set();
|
|
2371
2422
|
for (const obs of agentObservations) {
|
package/dist/index.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "adaptive-bitmask",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.4",
|
|
4
4
|
"description": "Sub-10ms coordination protocol for multi-agent systems. 85× bandwidth reduction through semantic bitmask encoding.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
8
|
+
"bin": {
|
|
9
|
+
"create-swarm": "./dist/cli/index.js"
|
|
10
|
+
},
|
|
8
11
|
"exports": {
|
|
9
12
|
".": {
|
|
10
13
|
"types": "./dist/index.d.ts",
|
|
@@ -23,14 +26,19 @@
|
|
|
23
26
|
"LICENSE"
|
|
24
27
|
],
|
|
25
28
|
"scripts": {
|
|
26
|
-
"build": "tsup src/index.ts src/ai/index.ts --format cjs,esm --dts --clean",
|
|
29
|
+
"build": "tsup src/index.ts src/ai/index.ts src/cli/index.ts --format cjs,esm --dts --clean",
|
|
27
30
|
"test": "vitest run",
|
|
28
31
|
"test:watch": "vitest",
|
|
29
32
|
"lint": "tsc --noEmit",
|
|
30
33
|
"benchmark": "npm run build && npm run benchmark:run",
|
|
31
34
|
"benchmark:run": "node benchmarks/run.mjs",
|
|
32
35
|
"benchmark:check": "node benchmarks/check.mjs",
|
|
33
|
-
"prepublishOnly": "npm run build"
|
|
36
|
+
"prepublishOnly": "npm run build",
|
|
37
|
+
"lean:build": "cd lean && lake build",
|
|
38
|
+
"lean:test": "cd lean && lake test",
|
|
39
|
+
"lean:format": "echo 'No Lean formatter configured (lake format is not available)'",
|
|
40
|
+
"lean:format:check": "echo 'No Lean formatter configured (lake format is not available)'",
|
|
41
|
+
"verify:math": "npm run lean:build && npm run lean:test"
|
|
34
42
|
},
|
|
35
43
|
"keywords": [
|
|
36
44
|
"multi-agent",
|
|
@@ -48,7 +56,7 @@
|
|
|
48
56
|
"license": "MIT",
|
|
49
57
|
"repository": {
|
|
50
58
|
"type": "git",
|
|
51
|
-
"url": "https://github.com/jverene/adaptive-bitmask"
|
|
59
|
+
"url": "git+https://github.com/jverene/adaptive-bitmask.git"
|
|
52
60
|
},
|
|
53
61
|
"peerDependencies": {
|
|
54
62
|
"ai": ">=4.0.0",
|
|
@@ -71,6 +79,7 @@
|
|
|
71
79
|
"@types/ws": "^8.18.1",
|
|
72
80
|
"ai": "^4.0.0",
|
|
73
81
|
"tsup": "^8.0.0",
|
|
82
|
+
"tsx": "^4.21.0",
|
|
74
83
|
"typescript": "^5.4.0",
|
|
75
84
|
"vitest": "^1.6.0",
|
|
76
85
|
"ws": "^8.19.0",
|
|
@@ -78,5 +87,9 @@
|
|
|
78
87
|
},
|
|
79
88
|
"engines": {
|
|
80
89
|
"node": ">=18"
|
|
90
|
+
},
|
|
91
|
+
"dependencies": {
|
|
92
|
+
"@clack/prompts": "^1.1.0",
|
|
93
|
+
"picocolors": "^1.1.1"
|
|
81
94
|
}
|
|
82
95
|
}
|