web-agent-bridge 2.3.0 → 2.3.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 (35) hide show
  1. package/package.json +12 -4
  2. package/public/commander-dashboard.html +243 -0
  3. package/public/css/premium.css +317 -317
  4. package/public/demo.html +259 -259
  5. package/public/index.html +644 -644
  6. package/public/mesh-dashboard.html +309 -382
  7. package/public/premium-dashboard.html +2487 -2487
  8. package/public/premium.html +791 -791
  9. package/public/script/wab.min.js +124 -87
  10. package/script/ai-agent-bridge.js +154 -84
  11. package/sdk/agent-mesh.js +287 -171
  12. package/sdk/commander.js +262 -0
  13. package/sdk/index.js +260 -260
  14. package/server/index.js +8 -1
  15. package/server/migrations/002_premium_features.sql +418 -418
  16. package/server/models/db.js +24 -5
  17. package/server/routes/admin-premium.js +671 -671
  18. package/server/routes/commander.js +316 -0
  19. package/server/routes/mesh.js +370 -201
  20. package/server/routes/premium-v2.js +686 -686
  21. package/server/routes/premium.js +724 -724
  22. package/server/services/agent-learning.js +230 -77
  23. package/server/services/agent-memory.js +625 -625
  24. package/server/services/agent-mesh.js +260 -67
  25. package/server/services/agent-symphony.js +548 -518
  26. package/server/services/commander.js +738 -0
  27. package/server/services/edge-compute.js +440 -0
  28. package/server/services/local-ai.js +389 -0
  29. package/server/services/plugins.js +747 -747
  30. package/server/services/self-healing.js +843 -843
  31. package/server/services/swarm.js +788 -788
  32. package/server/services/vision.js +871 -871
  33. package/public/admin/dashboard.html +0 -848
  34. package/public/admin/login.html +0 -84
  35. package/public/video/tutorial.mp4 +0 -0
@@ -9,6 +9,8 @@
9
9
  * - Each agent registers with the mesh and gets a mesh identity
10
10
  * - Agents publish messages to channels (broadcast or targeted)
11
11
  * - Message types: alert, discovery, tactic, request, response, vote
12
+ * - Votes are tallied with deadline-based collection
13
+ * - Stale agents auto-expire after missed heartbeats
12
14
  * - All communication is local — never leaves the WAB instance
13
15
  */
14
16
 
@@ -29,6 +31,7 @@ db.exec(`
29
31
  knowledge_count INTEGER DEFAULT 0,
30
32
  messages_sent INTEGER DEFAULT 0,
31
33
  messages_received INTEGER DEFAULT 0,
34
+ metadata TEXT DEFAULT '{}',
32
35
  created_at TEXT DEFAULT (datetime('now'))
33
36
  );
34
37
 
@@ -65,21 +68,49 @@ db.exec(`
65
68
  confidence REAL DEFAULT 1.0,
66
69
  source TEXT,
67
70
  verified_by TEXT,
71
+ verification_count INTEGER DEFAULT 0,
68
72
  access_count INTEGER DEFAULT 0,
69
73
  created_at TEXT DEFAULT (datetime('now')),
70
74
  updated_at TEXT DEFAULT (datetime('now'))
71
75
  );
72
76
 
77
+ CREATE TABLE IF NOT EXISTS mesh_votes (
78
+ id TEXT PRIMARY KEY,
79
+ vote_message_id TEXT NOT NULL,
80
+ voter_id TEXT NOT NULL,
81
+ choice TEXT NOT NULL,
82
+ weight REAL DEFAULT 1.0,
83
+ reason TEXT,
84
+ created_at TEXT DEFAULT (datetime('now')),
85
+ UNIQUE(vote_message_id, voter_id)
86
+ );
87
+
73
88
  CREATE INDEX IF NOT EXISTS idx_mesh_messages_channel ON mesh_messages(channel_id);
74
89
  CREATE INDEX IF NOT EXISTS idx_mesh_messages_sender ON mesh_messages(sender_id);
75
90
  CREATE INDEX IF NOT EXISTS idx_mesh_messages_target ON mesh_messages(target_id);
91
+ CREATE INDEX IF NOT EXISTS idx_mesh_messages_expires ON mesh_messages(expires_at);
76
92
  CREATE INDEX IF NOT EXISTS idx_mesh_knowledge_domain ON mesh_knowledge(domain);
77
93
  CREATE INDEX IF NOT EXISTS idx_mesh_knowledge_key ON mesh_knowledge(key);
94
+ CREATE INDEX IF NOT EXISTS idx_mesh_knowledge_type ON mesh_knowledge(knowledge_type);
78
95
  CREATE INDEX IF NOT EXISTS idx_mesh_agents_role ON mesh_agents(agent_role);
96
+ CREATE INDEX IF NOT EXISTS idx_mesh_agents_status ON mesh_agents(status);
97
+ CREATE INDEX IF NOT EXISTS idx_mesh_votes_msg ON mesh_votes(vote_message_id);
79
98
  `);
80
99
 
81
100
  // ─── Default Channels ───────────────────────────────────────────────
82
101
 
102
+ // Migration: add columns/tables that may not exist in older DBs
103
+ try { db.exec("ALTER TABLE mesh_agents ADD COLUMN metadata TEXT DEFAULT '{}'"); } catch (_) {}
104
+ try { db.exec("ALTER TABLE mesh_knowledge ADD COLUMN verified_by TEXT"); } catch (_) {}
105
+ try { db.exec("ALTER TABLE mesh_knowledge ADD COLUMN verification_count INTEGER DEFAULT 0"); } catch (_) {}
106
+ try { db.exec("ALTER TABLE mesh_knowledge ADD COLUMN access_count INTEGER DEFAULT 0"); } catch (_) {}
107
+ try { db.exec(`CREATE TABLE IF NOT EXISTS mesh_votes (
108
+ id TEXT PRIMARY KEY, vote_message_id TEXT NOT NULL, voter_id TEXT NOT NULL,
109
+ choice TEXT NOT NULL, weight REAL DEFAULT 1.0, reason TEXT,
110
+ created_at TEXT DEFAULT (datetime('now')), UNIQUE(vote_message_id, voter_id)
111
+ )`); } catch (_) {}
112
+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_mesh_votes_msg ON mesh_votes(vote_message_id)"); } catch (_) {}
113
+
83
114
  const DEFAULT_CHANNELS = [
84
115
  { name: 'alerts', description: 'Security alerts and site behavior warnings', channel_type: 'broadcast' },
85
116
  { name: 'discoveries', description: 'New site capabilities and schema changes', channel_type: 'broadcast' },
@@ -89,43 +120,64 @@ const DEFAULT_CHANNELS = [
89
120
  ];
90
121
 
91
122
  const _ensureChannels = db.transaction(() => {
92
- const insert = db.prepare(`INSERT OR IGNORE INTO mesh_channels (id, name, description, channel_type) VALUES (?, ?, ?, ?)`);
123
+ const insert = db.prepare('INSERT OR IGNORE INTO mesh_channels (id, name, description, channel_type) VALUES (?, ?, ?, ?)');
93
124
  for (const ch of DEFAULT_CHANNELS) {
94
125
  insert.run(crypto.randomUUID(), ch.name, ch.description, ch.channel_type);
95
126
  }
96
127
  });
97
128
  _ensureChannels();
98
129
 
130
+ // ─── Config ──────────────────────────────────────────────────────────
131
+
132
+ const STALE_THRESHOLD_SECONDS = 90;
133
+
99
134
  // ─── Prepared Statements ─────────────────────────────────────────────
100
135
 
101
136
  const stmts = {
102
- insertAgent: db.prepare(`INSERT INTO mesh_agents (id, site_id, agent_role, display_name, capabilities) VALUES (?, ?, ?, ?, ?)`),
103
- getAgent: db.prepare(`SELECT * FROM mesh_agents WHERE id = ?`),
104
- getAgentsByRole: db.prepare(`SELECT * FROM mesh_agents WHERE agent_role = ? AND status != 'offline'`),
105
- getActiveAgents: db.prepare(`SELECT * FROM mesh_agents WHERE status != 'offline' ORDER BY last_heartbeat DESC`),
106
- updateAgentStatus: db.prepare(`UPDATE mesh_agents SET status = ?, last_heartbeat = datetime('now') WHERE id = ?`),
107
- updateAgentCounters: db.prepare(`UPDATE mesh_agents SET messages_sent = messages_sent + ?, messages_received = messages_received + ?, knowledge_count = ? WHERE id = ?`),
108
- heartbeat: db.prepare(`UPDATE mesh_agents SET last_heartbeat = datetime('now'), status = 'active' WHERE id = ?`),
109
-
110
- getChannel: db.prepare(`SELECT * FROM mesh_channels WHERE name = ?`),
111
- getAllChannels: db.prepare(`SELECT * FROM mesh_channels`),
112
-
113
- insertMessage: db.prepare(`INSERT INTO mesh_messages (id, channel_id, sender_id, target_id, message_type, subject, payload, priority, ttl_seconds, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'))`),
114
- getMessages: db.prepare(`SELECT m.*, a.agent_role as sender_role, a.display_name as sender_name FROM mesh_messages m LEFT JOIN mesh_agents a ON m.sender_id = a.id WHERE m.channel_id = ? AND m.expires_at > datetime('now') ORDER BY m.created_at DESC LIMIT ?`),
115
- getMessagesForAgent: db.prepare(`SELECT m.*, a.agent_role as sender_role, a.display_name as sender_name FROM mesh_messages m LEFT JOIN mesh_agents a ON m.sender_id = a.id WHERE (m.target_id = ? OR m.target_id IS NULL) AND m.channel_id = ? AND m.acknowledged = 0 AND m.expires_at > datetime('now') ORDER BY m.priority DESC, m.created_at DESC LIMIT ?`),
116
- ackMessage: db.prepare(`UPDATE mesh_messages SET acknowledged = 1 WHERE id = ? AND target_id = ?`),
117
- countUnread: db.prepare(`SELECT COUNT(*) as count FROM mesh_messages WHERE (target_id = ? OR target_id IS NULL) AND acknowledged = 0 AND expires_at > datetime('now')`),
118
-
119
- insertKnowledge: db.prepare(`INSERT INTO mesh_knowledge (id, agent_id, knowledge_type, domain, key, value, confidence, source) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`),
120
- getKnowledge: db.prepare(`SELECT * FROM mesh_knowledge WHERE domain = ? AND key = ? ORDER BY confidence DESC, updated_at DESC LIMIT 1`),
121
- searchKnowledge: db.prepare(`SELECT * FROM mesh_knowledge WHERE domain = ? ORDER BY confidence DESC, access_count DESC LIMIT ?`),
122
- searchKnowledgeByType: db.prepare(`SELECT * FROM mesh_knowledge WHERE knowledge_type = ? ORDER BY confidence DESC LIMIT ?`),
123
- updateKnowledge: db.prepare(`UPDATE mesh_knowledge SET value = ?, confidence = ?, verified_by = ?, updated_at = datetime('now') WHERE id = ?`),
124
- touchKnowledge: db.prepare(`UPDATE mesh_knowledge SET access_count = access_count + 1 WHERE id = ?`),
125
- getAgentKnowledgeCount: db.prepare(`SELECT COUNT(*) as count FROM mesh_knowledge WHERE agent_id = ?`),
126
-
127
- cleanExpired: db.prepare(`DELETE FROM mesh_messages WHERE expires_at < datetime('now')`),
128
- getStats: db.prepare(`SELECT (SELECT COUNT(*) FROM mesh_agents WHERE status != 'offline') as active_agents, (SELECT COUNT(*) FROM mesh_messages WHERE expires_at > datetime('now')) as active_messages, (SELECT COUNT(*) FROM mesh_knowledge) as total_knowledge, (SELECT COUNT(DISTINCT domain) FROM mesh_knowledge) as known_domains`),
137
+ insertAgent: db.prepare('INSERT INTO mesh_agents (id, site_id, agent_role, display_name, capabilities, metadata) VALUES (?, ?, ?, ?, ?, ?)'),
138
+ getAgent: db.prepare('SELECT * FROM mesh_agents WHERE id = ?'),
139
+ getAgentsByRole: db.prepare("SELECT * FROM mesh_agents WHERE agent_role = ? AND status NOT IN ('offline','stale')"),
140
+ getActiveAgents: db.prepare("SELECT * FROM mesh_agents WHERE status NOT IN ('offline','stale') ORDER BY last_heartbeat DESC"),
141
+ getActiveAgentsBySite: db.prepare("SELECT * FROM mesh_agents WHERE site_id = ? AND status NOT IN ('offline','stale') ORDER BY last_heartbeat DESC"),
142
+ updateAgentStatus: db.prepare("UPDATE mesh_agents SET status = ?, last_heartbeat = datetime('now') WHERE id = ?"),
143
+ updateAgentMeta: db.prepare('UPDATE mesh_agents SET metadata = ? WHERE id = ?'),
144
+ heartbeat: db.prepare("UPDATE mesh_agents SET last_heartbeat = datetime('now'), status = 'active' WHERE id = ?"),
145
+ incrementSent: db.prepare('UPDATE mesh_agents SET messages_sent = messages_sent + 1 WHERE id = ?'),
146
+ incrementReceived: db.prepare('UPDATE mesh_agents SET messages_received = messages_received + 1 WHERE id = ?'),
147
+ updateKnowledgeCount: db.prepare('UPDATE mesh_agents SET knowledge_count = (SELECT COUNT(*) FROM mesh_knowledge WHERE agent_id = ?) WHERE id = ?'),
148
+ removeAgent: db.prepare("UPDATE mesh_agents SET status = 'offline' WHERE id = ?"),
149
+ markStaleAgents: db.prepare("UPDATE mesh_agents SET status = 'stale' WHERE status IN ('active','idle','busy') AND last_heartbeat < datetime('now', '-' || ? || ' seconds')"),
150
+
151
+ getChannel: db.prepare('SELECT * FROM mesh_channels WHERE name = ?'),
152
+ getAllChannels: db.prepare('SELECT * FROM mesh_channels'),
153
+ createChannel: db.prepare('INSERT OR IGNORE INTO mesh_channels (id, name, description, channel_type) VALUES (?, ?, ?, ?)'),
154
+
155
+ insertMessage: db.prepare("INSERT INTO mesh_messages (id, channel_id, sender_id, target_id, message_type, subject, payload, priority, ttl_seconds, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'))"),
156
+ getMessages: db.prepare("SELECT m.*, a.agent_role as sender_role, a.display_name as sender_name FROM mesh_messages m LEFT JOIN mesh_agents a ON m.sender_id = a.id WHERE m.channel_id = ? AND m.expires_at > datetime('now') ORDER BY m.created_at DESC LIMIT ?"),
157
+ getMessagesForAgent: db.prepare("SELECT m.*, a.agent_role as sender_role, a.display_name as sender_name FROM mesh_messages m LEFT JOIN mesh_agents a ON m.sender_id = a.id WHERE (m.target_id = ? OR m.target_id IS NULL) AND m.channel_id = ? AND m.acknowledged = 0 AND m.expires_at > datetime('now') ORDER BY m.priority DESC, m.created_at DESC LIMIT ?"),
158
+ ackMessageForAgent: db.prepare('UPDATE mesh_messages SET acknowledged = 1 WHERE id = ? AND (target_id = ? OR target_id IS NULL)'),
159
+ getMessage: db.prepare('SELECT * FROM mesh_messages WHERE id = ?'),
160
+ countUnread: db.prepare("SELECT COUNT(*) as count FROM mesh_messages WHERE (target_id = ? OR target_id IS NULL) AND acknowledged = 0 AND expires_at > datetime('now')"),
161
+ countUnreadByChannel: db.prepare("SELECT c.name as channel, COUNT(m.id) as count FROM mesh_messages m JOIN mesh_channels c ON m.channel_id = c.id WHERE (m.target_id = ? OR m.target_id IS NULL) AND m.acknowledged = 0 AND m.expires_at > datetime('now') GROUP BY c.name"),
162
+
163
+ insertKnowledge: db.prepare('INSERT INTO mesh_knowledge (id, agent_id, knowledge_type, domain, key, value, confidence, source) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'),
164
+ getKnowledge: db.prepare('SELECT * FROM mesh_knowledge WHERE domain = ? AND key = ? ORDER BY confidence DESC, updated_at DESC LIMIT 1'),
165
+ getKnowledgeById: db.prepare('SELECT * FROM mesh_knowledge WHERE id = ?'),
166
+ searchKnowledge: db.prepare('SELECT * FROM mesh_knowledge WHERE domain = ? ORDER BY confidence DESC, access_count DESC LIMIT ?'),
167
+ searchKnowledgeByType: db.prepare('SELECT * FROM mesh_knowledge WHERE knowledge_type = ? ORDER BY confidence DESC LIMIT ?'),
168
+ searchKnowledgeByAgent: db.prepare('SELECT * FROM mesh_knowledge WHERE agent_id = ? ORDER BY updated_at DESC LIMIT ?'),
169
+ updateKnowledgeConfidence: db.prepare("UPDATE mesh_knowledge SET confidence = ?, verified_by = ?, verification_count = verification_count + 1, updated_at = datetime('now') WHERE id = ?"),
170
+ updateKnowledgeValue: db.prepare("UPDATE mesh_knowledge SET value = ?, confidence = ?, updated_at = datetime('now') WHERE id = ?"),
171
+ touchKnowledge: db.prepare('UPDATE mesh_knowledge SET access_count = access_count + 1 WHERE id = ?'),
172
+ getAllKnowledgeDomains: db.prepare('SELECT domain, COUNT(*) as count, AVG(confidence) as avg_confidence FROM mesh_knowledge GROUP BY domain ORDER BY count DESC'),
173
+ getRecentKnowledge: db.prepare('SELECT * FROM mesh_knowledge ORDER BY updated_at DESC LIMIT ?'),
174
+
175
+ insertVote: db.prepare('INSERT OR REPLACE INTO mesh_votes (id, vote_message_id, voter_id, choice, weight, reason) VALUES (?, ?, ?, ?, ?, ?)'),
176
+ getVotesForMessage: db.prepare('SELECT v.*, a.agent_role as voter_role, a.display_name as voter_name FROM mesh_votes v LEFT JOIN mesh_agents a ON v.voter_id = a.id WHERE v.vote_message_id = ? ORDER BY v.created_at'),
177
+ countVotesForMessage: db.prepare('SELECT choice, SUM(weight) as total_weight, COUNT(*) as count FROM mesh_votes WHERE vote_message_id = ? GROUP BY choice ORDER BY total_weight DESC'),
178
+
179
+ cleanExpired: db.prepare("DELETE FROM mesh_messages WHERE expires_at < datetime('now')"),
180
+ getStats: db.prepare("SELECT (SELECT COUNT(*) FROM mesh_agents WHERE status NOT IN ('offline','stale')) as active_agents, (SELECT COUNT(*) FROM mesh_messages WHERE expires_at > datetime('now')) as active_messages, (SELECT COUNT(*) FROM mesh_knowledge) as total_knowledge, (SELECT COUNT(DISTINCT domain) FROM mesh_knowledge) as known_domains, (SELECT COUNT(*) FROM mesh_agents WHERE status = 'stale') as stale_agents, (SELECT COUNT(*) FROM mesh_votes) as total_votes"),
129
181
  };
130
182
 
131
183
  // ─── In-Memory Event Bus ─────────────────────────────────────────────
@@ -133,41 +185,72 @@ const stmts = {
133
185
  const _listeners = {};
134
186
 
135
187
  function _emit(event, data) {
136
- if (_listeners[event]) {
137
- for (const fn of _listeners[event]) {
138
- try { fn(data); } catch (_) { /* swallow */ }
188
+ const handlers = _listeners[event];
189
+ if (!handlers) return;
190
+ for (const fn of handlers) {
191
+ try { fn(data); } catch (err) {
192
+ console.error(`[mesh] event listener error on '${event}':`, err.message);
139
193
  }
140
194
  }
141
195
  }
142
196
 
143
- // ─── API ──────────────────────────────────────────────────────────────
197
+ // ─── Agent Management ─────────────────────────────────────────────────
144
198
 
145
- function registerAgent(siteId, role, displayName, capabilities = []) {
199
+ function registerAgent(siteId, role, displayName, capabilities = [], metadata = {}) {
146
200
  const id = crypto.randomUUID();
147
- stmts.insertAgent.run(id, siteId, role, displayName || role, JSON.stringify(capabilities));
148
- _emit('agent:joined', { agentId: id, role, displayName });
149
- return { id, role, displayName, status: 'idle' };
201
+ stmts.insertAgent.run(id, siteId, role, displayName || role, JSON.stringify(capabilities), JSON.stringify(metadata));
202
+ _emit('agent:joined', { agentId: id, role, displayName: displayName || role, siteId });
203
+ return { id, role, displayName: displayName || role, status: 'idle', siteId };
150
204
  }
151
205
 
152
- function heartbeat(agentId) {
153
- stmts.heartbeat.run(agentId);
206
+ function deregisterAgent(agentId) {
207
+ const agent = stmts.getAgent.get(agentId);
208
+ if (!agent) return false;
209
+ stmts.removeAgent.run(agentId);
210
+ _emit('agent:left', { agentId, role: agent.agent_role, displayName: agent.display_name });
154
211
  return true;
155
212
  }
156
213
 
214
+ function heartbeat(agentId) {
215
+ const result = stmts.heartbeat.run(agentId);
216
+ return result.changes > 0;
217
+ }
218
+
157
219
  function setAgentStatus(agentId, status) {
220
+ const validStatuses = ['active', 'idle', 'busy', 'offline'];
221
+ if (!validStatuses.includes(status)) return false;
158
222
  stmts.updateAgentStatus.run(status, agentId);
159
223
  if (status === 'offline') _emit('agent:left', { agentId });
160
224
  return true;
161
225
  }
162
226
 
163
- function getActiveAgents() {
164
- return stmts.getActiveAgents.all().map(_parseAgent);
227
+ function getAgent(agentId) {
228
+ const row = stmts.getAgent.get(agentId);
229
+ return row ? _parseAgent(row) : null;
230
+ }
231
+
232
+ function getActiveAgents(siteId) {
233
+ stmts.markStaleAgents.run(STALE_THRESHOLD_SECONDS);
234
+ const rows = siteId ? stmts.getActiveAgentsBySite.all(siteId) : stmts.getActiveAgents.all();
235
+ return rows.map(_parseAgent);
165
236
  }
166
237
 
167
238
  function getAgentsByRole(role) {
239
+ stmts.markStaleAgents.run(STALE_THRESHOLD_SECONDS);
168
240
  return stmts.getAgentsByRole.all(role).map(_parseAgent);
169
241
  }
170
242
 
243
+ function updateAgentMeta(agentId, metadata) {
244
+ const agent = stmts.getAgent.get(agentId);
245
+ if (!agent) return false;
246
+ const existing = JSON.parse(agent.metadata || '{}');
247
+ const merged = { ...existing, ...metadata };
248
+ stmts.updateAgentMeta.run(JSON.stringify(merged), agentId);
249
+ return true;
250
+ }
251
+
252
+ // ─── Messaging ────────────────────────────────────────────────────────
253
+
171
254
  function publish(senderId, channelName, messageType, subject, payload, options = {}) {
172
255
  const channel = stmts.getChannel.get(channelName);
173
256
  if (!channel) throw new Error(`Channel "${channelName}" not found`);
@@ -178,14 +261,12 @@ function publish(senderId, channelName, messageType, subject, payload, options =
178
261
  const targetId = options.targetId || null;
179
262
 
180
263
  stmts.insertMessage.run(id, channel.id, senderId, targetId, messageType, subject, JSON.stringify(payload), priority, ttl, ttl);
181
-
182
- // Update sender counters
183
- const kCount = stmts.getAgentKnowledgeCount.get(senderId);
184
- stmts.updateAgentCounters.run(1, 0, kCount ? kCount.count : 0, senderId);
264
+ stmts.incrementSent.run(senderId);
185
265
 
186
266
  const msg = { id, channelName, senderId, targetId, messageType, subject, payload, priority };
187
267
  _emit('message', msg);
188
268
  _emit(`message:${channelName}`, msg);
269
+ _emit(`message:${messageType}`, msg);
189
270
 
190
271
  return msg;
191
272
  }
@@ -193,19 +274,18 @@ function publish(senderId, channelName, messageType, subject, payload, options =
193
274
  function getMessages(channelName, limit = 50) {
194
275
  const channel = stmts.getChannel.get(channelName);
195
276
  if (!channel) return [];
196
- return stmts.getMessages.all(channel.id, limit).map(_parseMessage);
277
+ return stmts.getMessages.all(channel.id, Math.min(limit, 200)).map(_parseMessage);
197
278
  }
198
279
 
199
280
  function getMessagesForAgent(agentId, channelName, limit = 20) {
200
281
  const channel = stmts.getChannel.get(channelName);
201
282
  if (!channel) return [];
202
- return stmts.getMessagesForAgent.all(agentId, channel.id, limit).map(_parseMessage);
283
+ return stmts.getMessagesForAgent.all(agentId, channel.id, Math.min(limit, 100)).map(_parseMessage);
203
284
  }
204
285
 
205
286
  function acknowledge(agentId, messageId) {
206
- stmts.ackMessage.run(messageId, agentId);
207
- const kCount = stmts.getAgentKnowledgeCount.get(agentId);
208
- stmts.updateAgentCounters.run(0, 1, kCount ? kCount.count : 0, agentId);
287
+ stmts.ackMessageForAgent.run(messageId, agentId);
288
+ stmts.incrementReceived.run(agentId);
209
289
  return true;
210
290
  }
211
291
 
@@ -213,6 +293,10 @@ function getUnreadCount(agentId) {
213
293
  return stmts.countUnread.get(agentId).count;
214
294
  }
215
295
 
296
+ function getUnreadByChannel(agentId) {
297
+ return stmts.countUnreadByChannel.all(agentId);
298
+ }
299
+
216
300
  // ─── Knowledge Sharing ───────────────────────────────────────────────
217
301
 
218
302
  function shareKnowledge(agentId, knowledgeType, domain, key, value, confidence = 1.0) {
@@ -221,12 +305,8 @@ function shareKnowledge(agentId, knowledgeType, domain, key, value, confidence =
221
305
  const source = agent ? agent.display_name : agentId;
222
306
 
223
307
  stmts.insertKnowledge.run(id, agentId, knowledgeType, domain, key, JSON.stringify(value), confidence, source);
308
+ stmts.updateKnowledgeCount.run(agentId, agentId);
224
309
 
225
- // Update agent knowledge count
226
- const kCount = stmts.getAgentKnowledgeCount.get(agentId);
227
- stmts.updateAgentCounters.run(0, 0, kCount ? kCount.count : 0, agentId);
228
-
229
- // Auto-publish discovery to mesh
230
310
  publish(agentId, 'discoveries', 'discovery', `New ${knowledgeType}: ${key}`, {
231
311
  knowledgeId: id, knowledgeType, domain, key, confidence
232
312
  }, { ttl: 600 });
@@ -244,21 +324,122 @@ function queryKnowledge(domain, key) {
244
324
  return null;
245
325
  }
246
326
 
327
+ function getKnowledgeById(id) {
328
+ const row = stmts.getKnowledgeById.get(id);
329
+ return row ? _parseKnowledge(row) : null;
330
+ }
331
+
247
332
  function searchKnowledge(domain, limit = 20) {
248
- return stmts.searchKnowledge.all(domain, limit).map(_parseKnowledge);
333
+ return stmts.searchKnowledge.all(domain, Math.min(limit, 100)).map(_parseKnowledge);
249
334
  }
250
335
 
251
336
  function searchKnowledgeByType(type, limit = 20) {
252
- return stmts.searchKnowledgeByType.all(type, limit).map(_parseKnowledge);
337
+ return stmts.searchKnowledgeByType.all(type, Math.min(limit, 100)).map(_parseKnowledge);
338
+ }
339
+
340
+ function searchKnowledgeByAgent(agentId, limit = 20) {
341
+ return stmts.searchKnowledgeByAgent.all(agentId, Math.min(limit, 100)).map(_parseKnowledge);
342
+ }
343
+
344
+ function getKnowledgeDomains() {
345
+ return stmts.getAllKnowledgeDomains.all();
346
+ }
347
+
348
+ function getRecentKnowledge(limit = 30) {
349
+ return stmts.getRecentKnowledge.all(Math.min(limit, 100)).map(_parseKnowledge);
253
350
  }
254
351
 
255
352
  function verifyKnowledge(knowledgeId, verifierAgentId, newConfidence) {
353
+ const existing = stmts.getKnowledgeById.get(knowledgeId);
354
+ if (!existing) return false;
355
+
256
356
  const agent = stmts.getAgent.get(verifierAgentId);
257
357
  const verifier = agent ? agent.display_name : verifierAgentId;
258
- stmts.updateKnowledge.run(null, newConfidence, verifier, knowledgeId);
358
+
359
+ // Weighted running average: merge existing confidence with verifier's assessment
360
+ const count = existing.verification_count || 0;
361
+ const mergedConfidence = count > 0
362
+ ? (existing.confidence * count + newConfidence) / (count + 1)
363
+ : (existing.confidence + newConfidence) / 2;
364
+
365
+ stmts.updateKnowledgeConfidence.run(
366
+ Math.min(0.99, Math.max(0.01, mergedConfidence)),
367
+ verifier,
368
+ knowledgeId
369
+ );
370
+
371
+ _emit('knowledge:verified', { knowledgeId, verifier, newConfidence: mergedConfidence });
372
+ return { knowledgeId, confidence: mergedConfidence, verifiedBy: verifier };
373
+ }
374
+
375
+ function updateKnowledge(knowledgeId, newValue, newConfidence) {
376
+ const existing = stmts.getKnowledgeById.get(knowledgeId);
377
+ if (!existing) return false;
378
+ stmts.updateKnowledgeValue.run(JSON.stringify(newValue), newConfidence, knowledgeId);
259
379
  return true;
260
380
  }
261
381
 
382
+ // ─── Voting ──────────────────────────────────────────────────────────
383
+
384
+ function createVote(senderId, subject, options, ttl = 60) {
385
+ return publish(senderId, 'votes', 'vote', subject, {
386
+ options,
387
+ deadline: new Date(Date.now() + ttl * 1000).toISOString()
388
+ }, { ttl, priority: 1 });
389
+ }
390
+
391
+ function castVote(voteMessageId, voterId, choice, weight = 1.0, reason = '') {
392
+ const message = stmts.getMessage.get(voteMessageId);
393
+ if (!message) throw new Error('Vote message not found');
394
+
395
+ const payload = JSON.parse(message.payload || '{}');
396
+ if (payload.options && Array.isArray(payload.options) && !payload.options.includes(choice)) {
397
+ throw new Error(`Invalid choice. Options: ${payload.options.join(', ')}`);
398
+ }
399
+
400
+ // Check deadline
401
+ if (payload.deadline && new Date(payload.deadline) < new Date()) {
402
+ throw new Error('Voting deadline has passed');
403
+ }
404
+
405
+ const id = crypto.randomUUID();
406
+ stmts.insertVote.run(id, voteMessageId, voterId, choice, weight, reason);
407
+ _emit('vote:cast', { voteMessageId, voterId, choice });
408
+ return { id, voteMessageId, choice, weight };
409
+ }
410
+
411
+ function tallyVotes(voteMessageId) {
412
+ const results = stmts.countVotesForMessage.all(voteMessageId);
413
+ const votes = stmts.getVotesForMessage.all(voteMessageId);
414
+
415
+ if (results.length === 0) {
416
+ return { voteMessageId, totalVoters: 0, results: [], winner: null, votes: [] };
417
+ }
418
+
419
+ const totalWeight = results.reduce((sum, r) => sum + r.total_weight, 0);
420
+ const ranked = results.map(r => ({
421
+ choice: r.choice,
422
+ votes: r.count,
423
+ weight: r.total_weight,
424
+ percentage: totalWeight > 0 ? Math.round((r.total_weight / totalWeight) * 10000) / 100 : 0
425
+ }));
426
+
427
+ return {
428
+ voteMessageId,
429
+ totalVoters: votes.length,
430
+ totalWeight,
431
+ results: ranked,
432
+ winner: ranked[0]?.choice || null,
433
+ margin: ranked.length > 1 ? ranked[0].percentage - ranked[1].percentage : 100,
434
+ votes: votes.map(v => ({
435
+ voter: v.voter_name || v.voter_role || v.voter_id,
436
+ choice: v.choice,
437
+ weight: v.weight,
438
+ reason: v.reason
439
+ }))
440
+ };
441
+ }
442
+
262
443
  // ─── Alerts & Tactics ────────────────────────────────────────────────
263
444
 
264
445
  function broadcastAlert(senderId, subject, details, priority = 2) {
@@ -285,8 +466,12 @@ function requestHelp(senderId, subject, question, targetRole = null) {
285
466
  return [publish(senderId, 'alerts', 'request', subject, { question }, opts)];
286
467
  }
287
468
 
288
- function vote(senderId, subject, options) {
289
- return publish(senderId, 'votes', 'vote', subject, { options, votes: {} }, { ttl: 60, priority: 1 });
469
+ // ─── Channels ────────────────────────────────────────────────────────
470
+
471
+ function createChannel(name, description, channelType = 'broadcast') {
472
+ const id = crypto.randomUUID();
473
+ stmts.createChannel.run(id, name, description, channelType);
474
+ return { id, name, description, channelType };
290
475
  }
291
476
 
292
477
  // ─── Event Subscriptions ─────────────────────────────────────────────
@@ -305,7 +490,9 @@ function off(event, callback) {
305
490
  // ─── Maintenance ─────────────────────────────────────────────────────
306
491
 
307
492
  function cleanup() {
308
- stmts.cleanExpired.run();
493
+ const result = stmts.cleanExpired.run();
494
+ stmts.markStaleAgents.run(STALE_THRESHOLD_SECONDS);
495
+ return { expiredMessages: result.changes };
309
496
  }
310
497
 
311
498
  function getStats() {
@@ -320,7 +507,11 @@ function getChannels() {
320
507
 
321
508
  function _parseAgent(row) {
322
509
  if (!row) return null;
323
- return { ...row, capabilities: JSON.parse(row.capabilities || '[]') };
510
+ return {
511
+ ...row,
512
+ capabilities: JSON.parse(row.capabilities || '[]'),
513
+ metadata: JSON.parse(row.metadata || '{}')
514
+ };
324
515
  }
325
516
 
326
517
  function _parseMessage(row) {
@@ -333,14 +524,16 @@ function _parseKnowledge(row) {
333
524
  return { ...row, value: JSON.parse(row.value || '{}') };
334
525
  }
335
526
 
336
- // Cleanup expired messages every 2 minutes
337
527
  const _cleanupInterval = setInterval(cleanup, 120000);
338
528
  if (_cleanupInterval.unref) _cleanupInterval.unref();
339
529
 
340
530
  module.exports = {
341
- registerAgent, heartbeat, setAgentStatus, getActiveAgents, getAgentsByRole,
342
- publish, getMessages, getMessagesForAgent, acknowledge, getUnreadCount,
343
- shareKnowledge, queryKnowledge, searchKnowledge, searchKnowledgeByType, verifyKnowledge,
344
- broadcastAlert, shareTactic, requestHelp, vote,
345
- on, off, cleanup, getStats, getChannels,
531
+ registerAgent, deregisterAgent, heartbeat, setAgentStatus,
532
+ getAgent, getActiveAgents, getAgentsByRole, updateAgentMeta,
533
+ publish, getMessages, getMessagesForAgent, acknowledge, getUnreadCount, getUnreadByChannel,
534
+ shareKnowledge, queryKnowledge, getKnowledgeById, searchKnowledge, searchKnowledgeByType,
535
+ searchKnowledgeByAgent, getKnowledgeDomains, getRecentKnowledge, verifyKnowledge, updateKnowledge,
536
+ createVote, castVote, tallyVotes,
537
+ broadcastAlert, shareTactic, requestHelp,
538
+ createChannel, on, off, cleanup, getStats, getChannels,
346
539
  };