Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(agentbbs): cross-host federation β€” signed envelopes, pinned peers, union merge (#3251)

rUv72df96c29714
diff --git a/.github/workflows/no-agentbbs-smoke.yml b/.github/workflows/no-agentbbs-smoke.yml
index ca9edb4bc7..8c1c4a7820 100644
--- a/.github/workflows/no-agentbbs-smoke.yml
+++ b/.github/workflows/no-agentbbs-smoke.yml
@@ -90,7 +90,11 @@ jobs:
# use a dynamic import('agentbbs'). Static `import ... from 'agentbbs'`
# is forbidden β€” it would make the dep mandatory.
run: |
- node -e "
+ # Fed via a QUOTED heredoc: bash performs no expansion inside
+ # <<'RULE2', so backslashes in regexes and backticks in comments
+ # reach node verbatim. (As `node -e "..."` they did not: bash
+ # collapsed \\ escapes and ran backticked comment text as commands.)
+ node - <<'RULE2'
const { readFileSync, readdirSync, statSync } = require('fs');
const { join } = require('path');
const root = 'v3/@claude-flow/cli/src';
@@ -103,7 +107,7 @@ jobs:
if (!p.endsWith('.ts')) continue;
const src = readFileSync(p, 'utf-8');
// Static import β€” forbidden:
- if (/^\s*import\s+[^;]*from\s+['\"]agentbbs['\"]/m.test(src)) {
+ if (/^\s*import\s+[^;]*from\s+['"]agentbbs['"]/m.test(src)) {
offenders.push({ file: p, reason: 'static import of agentbbs' });
continue;
}
@@ -120,11 +124,23 @@ jobs:
const stripped = src
.replace(/^\s*\/\/.*$/gm, '') // single-line comments
.replace(/\/\*[\s\S]*?\*\//g, '') // block comments
- .replace(/export\s+\{[^}]*agentbbsTools[^}]*\}\s+from\s+['\"][^'\"]+agentbbs-tools[^'\"]*['\"];?/g, '')
- .replace(/import\s+\{[^}]*agentbbsTools[^}]*\}\s+from\s+['\"][^'\"]+agentbbs-tools[^'\"]*['\"];?/g, '')
- .replace(/\.\.\.agentbbsTools,?/g, '');
+ .replace(/export\s+\{[^}]*agentbbsTools[^}]*\}\s+from\s+['"][^'"]+agentbbs-tools[^'"]*['"];?/g, '')
+ .replace(/import\s+\{[^}]*agentbbsTools[^}]*\}\s+from\s+['"][^'"]+agentbbs-tools[^'"]*['"];?/g, '')
+ .replace(/\.\.\.agentbbsTools,?/g, '')
+ // Phase 2 federation uses 'agentbbs' as a wire namespace, not a
+ // package: the '/agentbbs/v1/...' HTTP route prefix and the
+ // 'agentbbs:<kind>:' hash domain-separators. Neither loads the
+ // optional dependency, so neither needs a loadAgentbbs guard.
+ // The static-import check above is untouched and still the
+ // real gate β€” this only stops the catch-all heuristic firing
+ // on string literals that never reach a module resolver.
+ // NOTE: no backslashes in these patterns on purpose β€” this
+ // whole script is a bash double-quoted string, which would
+ // collapse '\\?' to '\?' (a literal '?') before node sees it.
+ .replace(/agentbbs(?=.?[/]v1)/g, '')
+ .replace(/agentbbs(?=:[a-z]+:)/g, '');
if (/agentbbs/.test(stripped)) {
- const guarded = /loadAgentbbs|import\(['\"]agentbbs['\"]\)/m.test(src);
+ const guarded = /loadAgentbbs|import\(['"]agentbbs['"]\)/m.test(src);
if (!guarded) {
offenders.push({ file: p, reason: 'agentbbs reference without loadAgentbbs/dynamic import guard' });
}
@@ -139,7 +155,7 @@ jobs:
process.exit(1);
}
console.log('OK β€” every agentbbs reference under ' + root + ' is dynamically guarded.');
- "
+ RULE2
- uses: pnpm/action-setup@v4
with:
diff --git a/v3/@claude-flow/cli/__tests__/agentbbs-federation.test.ts b/v3/@claude-flow/cli/__tests__/agentbbs-federation.test.ts
new file mode 100644
index 0000000000..d6c53b5d0d
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/agentbbs-federation.test.ts
@@ -0,0 +1,387 @@
+/**
+ * agentbbs Phase 2 cross-host federation.
+ *
+ * The happy path here is small; most of this file is the trust boundary.
+ * Merge ingests bytes from another machine, so the tests that matter are the
+ * ones that prove a hostile peer cannot get an envelope past verification β€”
+ * forged signatures, key substitution, replay, oversize, hop exhaustion, and
+ * cross-room injection.
+ *
+ * Two nodes are run against real temp directories and a real HTTP server, so
+ * this exercises the actual transport rather than a mocked one.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, existsSync, readFileSync, statSync, appendFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import type { Server } from 'node:http';
+
+import {
+ getNodeIdentity,
+ signEnvelope,
+ verifyEnvelope,
+ canonicalEnvelopeBytes,
+ addPeer,
+ removePeer,
+ readPeers,
+ readEnvelopes,
+ mergeEnvelopes,
+ syncRoomFromPeer,
+ serveFederation,
+ validatePeerUrl,
+ validateRoomId,
+ MAX_HOPS,
+ MAX_ENVELOPE_BYTES,
+ type SignedEnvelope,
+} from '../src/mcp-tools/agentbbs-federation.js';
+
+let dirA: string, dirB: string;
+const servers: Server[] = [];
+
+function tmp(p: string) { return mkdtempSync(join(tmpdir(), p)); }
+
+function envelope(over: Partial<SignedEnvelope> = {}): SignedEnvelope {
+ return {
+ envelopeId: 'e-' + Math.random().toString(36).slice(2, 10),
+ roomId: 'sales-dd6531eb',
+ seq: 1,
+ msgType: 'Note',
+ payload: { hello: 'world' },
+ timestamp: '2026-09-09T00:00:00.000Z',
+ ...over,
+ };
+}
+
+beforeEach(() => { dirA = tmp('abbs-a-'); dirB = tmp('abbs-b-'); });
+afterEach(() => {
+ for (const s of servers.splice(0)) { try { s.close(); } catch { /* already closed */ } }
+ for (const d of [dirA, dirB]) { try { rmSync(d, { recursive: true, force: true }); } catch { /* gone */ } }
+});
+
+describe('node identity', () => {
+ it('creates a stable identity and reuses it across calls', async () => {
+ const a = await getNodeIdentity(dirA);
+ const b = await getNodeIdentity(dirA);
+ expect(a.nodeId).toBe(b.nodeId);
+ expect(a.nodeId).toMatch(/^[0-9a-f]{16}$/);
+ expect(a.publicKey).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ it('gives different hosts different identities', async () => {
+ const a = await getNodeIdentity(dirA);
+ const b = await getNodeIdentity(dirB);
+ expect(a.nodeId).not.toBe(b.nodeId);
+ });
+
+ it('persists the private key 0600 and never widens it', async () => {
+ await getNodeIdentity(dirA);
+ const mode = statSync(join(dirA, 'node-identity.json')).mode & 0o777;
+ expect(mode).toBe(0o600);
+ });
+
+ it('rejects a malformed identity file rather than trusting it', async () => {
+ await getNodeIdentity(dirA);
+ const p = join(dirA, 'node-identity.json');
+ const bad = JSON.parse(readFileSync(p, 'utf-8'));
+ bad.nodeId = 'not-hex';
+ require('node:fs').writeFileSync(p, JSON.stringify(bad));
+ await expect(getNodeIdentity(dirA)).rejects.toThrow(/malformed/);
+ });
+});
+
+describe('signing and verification', () => {
+ it('signs and verifies a round trip', async () => {
+ const id = await getNodeIdentity(dirA);
+ const signed = await signEnvelope(dirA, envelope());
+ expect(signed.origin).toBe(id.nodeId);
+ expect(await verifyEnvelope(signed, id.publicKey)).toBe(true);
+ });
+
+ it('survives a JSON round trip β€” the receiver reconstructs identical bytes', async () => {
+ const id = await getNodeIdentity(dirA);
+ const signed = await signEnvelope(dirA, envelope({ payload: { b: 2, a: 1, nested: { z: 1, y: [3, 2] } } }));
+ const overWire = JSON.parse(JSON.stringify(signed));
+ expect(await verifyEnvelope(overWire, id.publicKey)).toBe(true);
+ });
+
+ it('canonicalizes payload key order, so equal values sign equally', () => {
+ // Pin envelopeId β€” the helper randomizes it, and we are isolating payload
+ // key order as the only difference between the two inputs.
+ const one = canonicalEnvelopeBytes(envelope({ envelopeId: 'fixed', payload: { a: 1, b: 2 } }));
+ const two = canonicalEnvelopeBytes(envelope({ envelopeId: 'fixed', payload: { b: 2, a: 1 } }));
+ expect(Buffer.from(one).toString()).toBe(Buffer.from(two).toString());
+ });
+
+ it('excludes hops from the signature so relaying does not invalidate it', async () => {
+ const id = await getNodeIdentity(dirA);
+ const signed = await signEnvelope(dirA, envelope());
+ const relayed = { ...signed, hops: 3 };
+ expect(await verifyEnvelope(relayed, id.publicKey)).toBe(true);
+ });
+
+ describe('adversarial', () => {
+ it('rejects a tampered payload', async () => {
+ const id = await getNodeIdentity(dirA);
+ const signed = await signEnvelope(dirA, envelope());
+ expect(await verifyEnvelope({ ...signed, payload: { hello: 'tampered' } }, id.publicKey)).toBe(false);
+ });
+
+ it('rejects a tampered origin β€” you cannot claim to be another node', async () => {
+ const id = await getNodeIdentity(dirA);
+ const signed = await signEnvelope(dirA, envelope());
+ expect(await verifyEnvelope({ ...signed, origin: 'deadbeefdeadbeef' }, id.publicKey)).toBe(false);
+ });
+
+ it('rejects verification against a different key (key substitution)', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const signedByA = await signEnvelope(dirA, envelope());
+ expect(await verifyEnvelope(signedByA, idB.publicKey)).toBe(false);
+ });
+
+ it('rejects an unsigned or malformed-signature envelope', async () => {
+ const id = await getNodeIdentity(dirA);
+ expect(await verifyEnvelope(envelope(), id.publicKey)).toBe(false);
+ expect(await verifyEnvelope(envelope({ signature: 'zz' }), id.publicKey)).toBe(false);
+ expect(await verifyEnvelope(envelope({ signature: 'a'.repeat(128) }), id.publicKey)).toBe(false);
+ });
+ });
+});
+
+describe('peer registry', () => {
+ const KEY = 'a'.repeat(64);
+
+ it('pins a peer and lists it', () => {
+ const p = addPeer(dirA, { nodeId: '0123456789abcdef', url: 'http://127.0.0.1:9999', publicKey: KEY });
+ expect(p.nodeId).toBe('0123456789abcdef');
+ expect(readPeers(dirA)).toHaveLength(1);
+ expect(removePeer(dirA, '0123456789abcdef')).toBe(true);
+ expect(readPeers(dirA)).toHaveLength(0);
+ });
+
+ it('refuses to silently re-pin a known nodeId to a different key', () => {
+ addPeer(dirA, { nodeId: '0123456789abcdef', url: 'http://127.0.0.1:1', publicKey: KEY });
+ expect(() => addPeer(dirA, { nodeId: '0123456789abcdef', url: 'http://127.0.0.1:1', publicKey: 'b'.repeat(64) }))
+ .toThrow(/already pinned/);
+ });
+
+ it('rejects malformed identifiers and hostile URLs', () => {
+ expect(() => addPeer(dirA, { nodeId: 'short', url: 'http://x', publicKey: KEY })).toThrow(/nodeId/);
+ expect(() => addPeer(dirA, { nodeId: '0123456789abcdef', url: 'http://x', publicKey: 'nothex' })).toThrow(/publicKey/);
+ expect(() => validatePeerUrl('file:///etc/passwd')).toThrow(/http or https/);
+ expect(() => validatePeerUrl('http://user:pw@host')).toThrow(/credentials/);
+ expect(() => validatePeerUrl('not a url')).toThrow();
+ });
+
+ it('rejects room ids that could escape the log directory', () => {
+ expect(() => validateRoomId('../../etc/passwd')).toThrow();
+ expect(() => validateRoomId('a/../../b')).toThrow(/\.\./);
+ expect(() => validateRoomId('')).toThrow();
+ expect(() => validateRoomId('x'.repeat(129))).toThrow(/128/);
+ });
+});
+
+describe('union merge', () => {
+ it('merges verified envelopes from a peer', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const e1 = await signEnvelope(dirB, envelope({ seq: 1 }));
+ const e2 = await signEnvelope(dirB, envelope({ seq: 2 }));
+ const r = await mergeEnvelopes(dirA, 'sales-dd6531eb', [e1, e2], idB.publicKey);
+ expect(r.merged).toBe(2);
+ expect(readEnvelopes(dirA, 'sales-dd6531eb')).toHaveLength(2);
+ });
+
+ it('is idempotent β€” replaying the same batch merges nothing new', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const e1 = await signEnvelope(dirB, envelope());
+ await mergeEnvelopes(dirA, 'sales-dd6531eb', [e1], idB.publicKey);
+ const again = await mergeEnvelopes(dirA, 'sales-dd6531eb', [e1], idB.publicKey);
+ expect(again.merged).toBe(0);
+ expect(again.skippedDuplicate).toBe(1);
+ expect(readEnvelopes(dirA, 'sales-dd6531eb')).toHaveLength(1);
+ });
+
+ it('is order independent β€” A then B equals B then A', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const e1 = await signEnvelope(dirB, envelope({ seq: 1 }));
+ const e2 = await signEnvelope(dirB, envelope({ seq: 2 }));
+ const forward = tmp('abbs-f-'); const backward = tmp('abbs-r-');
+ try {
+ await mergeEnvelopes(forward, 'sales-dd6531eb', [e1, e2], idB.publicKey);
+ await mergeEnvelopes(backward, 'sales-dd6531eb', [e2, e1], idB.publicKey);
+ const ids = (d: string) => readEnvelopes(d, 'sales-dd6531eb').map(e => e.envelopeId).sort();
+ expect(ids(forward)).toEqual(ids(backward));
+ } finally {
+ rmSync(forward, { recursive: true, force: true });
+ rmSync(backward, { recursive: true, force: true });
+ }
+ });
+
+ describe('adversarial', () => {
+ it('drops forged envelopes rather than replicating them', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const good = await signEnvelope(dirB, envelope());
+ const forged = { ...good, envelopeId: 'forged-1', payload: { hello: 'evil' } };
+ const r = await mergeEnvelopes(dirA, 'sales-dd6531eb', [forged], idB.publicKey);
+ expect(r.merged).toBe(0);
+ expect(r.skippedUnverified).toBe(1);
+ expect(readEnvelopes(dirA, 'sales-dd6531eb')).toHaveLength(0);
+ });
+
+ it('drops envelopes signed by a key other than the pinned one', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const rogue = tmp('abbs-rogue-');
+ try {
+ const signedByRogue = await signEnvelope(rogue, envelope());
+ const r = await mergeEnvelopes(dirA, 'sales-dd6531eb', [signedByRogue], idB.publicKey);
+ expect(r.merged).toBe(0);
+ expect(r.skippedUnverified).toBe(1);
+ } finally { rmSync(rogue, { recursive: true, force: true }); }
+ });
+
+ it('drops cross-room injection β€” an envelope for another room', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const other = await signEnvelope(dirB, envelope({ roomId: 'finance-f6552ffe' }));
+ const r = await mergeEnvelopes(dirA, 'sales-dd6531eb', [other], idB.publicKey);
+ expect(r.merged).toBe(0);
+ expect(r.skippedUnverified).toBe(1);
+ });
+
+ it('drops envelopes at or past the hop limit', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const looped = await signEnvelope(dirB, envelope());
+ const r = await mergeEnvelopes(dirA, 'sales-dd6531eb', [{ ...looped, hops: MAX_HOPS }], idB.publicKey);
+ expect(r.merged).toBe(0);
+ expect(r.skippedHopLimit).toBe(1);
+ });
+
+ it('increments hops on merge so a cycle terminates', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const e = await signEnvelope(dirB, envelope());
+ await mergeEnvelopes(dirA, 'sales-dd6531eb', [e], idB.publicKey);
+ expect(readEnvelopes(dirA, 'sales-dd6531eb')[0].hops).toBe(1);
+ });
+
+ it('drops oversize envelopes', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const big = await signEnvelope(dirB, envelope({ payload: { blob: 'x'.repeat(MAX_ENVELOPE_BYTES) } }));
+ const r = await mergeEnvelopes(dirA, 'sales-dd6531eb', [big], idB.publicKey);
+ expect(r.merged).toBe(0);
+ expect(r.skippedOversize).toBe(1);
+ });
+
+ it('tolerates malformed rows without throwing', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const r = await mergeEnvelopes(dirA, 'sales-dd6531eb', [null as any, {} as any, 'x' as any], idB.publicKey);
+ expect(r.merged).toBe(0);
+ expect(r.skippedUnverified).toBe(3);
+ });
+
+ it('skips corrupt lines already in the local log', async () => {
+ const idB = await getNodeIdentity(dirB);
+ appendFileSync(join(dirA, 'room-sales-dd6531eb.jsonl'), 'not json\n');
+ const e = await signEnvelope(dirB, envelope());
+ const r = await mergeEnvelopes(dirA, 'sales-dd6531eb', [e], idB.publicKey);
+ expect(r.merged).toBe(1);
+ });
+ });
+});
+
+describe('http transport (two real nodes)', () => {
+ it('serves envelopes and a peer pulls, verifies and merges them', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const e1 = await signEnvelope(dirB, envelope({ seq: 1 }));
+ const e2 = await signEnvelope(dirB, envelope({ seq: 2 }));
+ appendFileSync(join(dirB, 'room-sales-dd6531eb.jsonl'), JSON.stringify(e1) + '\n' + JSON.stringify(e2) + '\n');
+
+ const { server, port } = await serveFederation(dirB, { port: 0 });
+ servers.push(server);
+
+ addPeer(dirA, { nodeId: idB.nodeId, url: `http://127.0.0.1:${port}`, publicKey: idB.publicKey });
+ const peer = readPeers(dirA)[0];
+ const r = await syncRoomFromPeer(dirA, peer, 'sales-dd6531eb');
+
+ expect(r.merged).toBe(2);
+ expect(readEnvelopes(dirA, 'sales-dd6531eb')).toHaveLength(2);
+ expect(readPeers(dirA)[0].lastSeq?.['sales-dd6531eb']).toBe(2);
+ });
+
+ it('a second sync is a no-op β€” since= advances', async () => {
+ const idB = await getNodeIdentity(dirB);
+ const e1 = await signEnvelope(dirB, envelope({ seq: 1 }));
+ appendFileSync(join(dirB, 'room-sales-dd6531eb.jsonl'), JSON.stringify(e1) + '\n');
+ const { server, port } = await serveFederation(dirB, { port: 0 });
+ servers.push(server);
+ addPeer(dirA, { nodeId: idB.nodeId, url: `http://127.0.0.1:${port}`, publicKey: idB.publicKey });
+
+ await syncRoomFromPeer(dirA, readPeers(dirA)[0], 'sales-dd6531eb');
+ const second = await syncRoomFromPeer(dirA, readPeers(dirA)[0], 'sales-dd6531eb');
+ expect(second.merged).toBe(0);
+ expect(readEnvelopes(dirA, 'sales-dd6531eb')).toHaveLength(1);
+ });
+
+ it('never serves the private key', async () => {
+ await getNodeIdentity(dirB);
+ const { server, port } = await serveFederation(dirB, { port: 0 });
+ servers.push(server);
+ const res = await fetch(`http://127.0.0.1:${port}/agentbbs/v1/identity`);
+ const body = await res.json() as Record<string, unknown>;
+ expect(body.publicKey).toMatch(/^[0-9a-f]{64}$/);
+ expect(body.privateKey).toBeUndefined();
+ expect(JSON.stringify(body)).not.toContain(JSON.parse(readFileSync(join(dirB, 'node-identity.json'), 'utf-8')).privateKey);
+ });
+
+ it('binds loopback by default rather than a routable interface', async () => {
+ const { server, host } = await serveFederation(dirB, { port: 0 });
+ servers.push(server);
+ expect(host).toBe('127.0.0.1');
+ });
+
+ it('is read only β€” mutating verbs are refused', async () => {
+ const { server, port } = await serveFederation(dirB, { port: 0 });
+ servers.push(server);
+ for (const method of ['POST', 'PUT', 'DELETE', 'PATCH']) {
+ const res = await fetch(`http://127.0.0.1:${port}/agentbbs/v1/rooms/x/envelopes`, { method });
+ expect(res.status).toBe(405);
+ }
+ });
+
+ it('rejects a traversing roomId at the HTTP boundary', async () => {
+ const { server, port } = await serveFederation(dirB, { port: 0 });
+ servers.push(server);
+ const res = await fetch(`http://127.0.0.1:${port}/agentbbs/v1/rooms/${encodeURIComponent('../../etc/passwd')}/envelopes`);
+ expect(res.status).toBe(400);
+ });
+
+ it('surfaces an unreachable peer as an error instead of hanging', async () => {
+ const idB = await getNodeIdentity(dirB);
+ addPeer(dirA, { nodeId: idB.nodeId, url: 'http://127.0.0.1:1', publicKey: idB.publicKey });
+ await expect(syncRoomFromPeer(dirA, readPeers(dirA)[0], 'sales-dd6531eb')).rejects.toThrow();
+ });
+});
+
+describe('convergence', () => {
+ it('two nodes that each publish converge on the same set after mutual sync', async () => {
+ const idA = await getNodeIdentity(dirA);
+ const idB = await getNodeIdentity(dirB);
+ const room = 'sales-dd6531eb';
+
+ const a1 = await signEnvelope(dirA, envelope({ seq: 1, payload: { from: 'A' } }));
+ const b1 = await signEnvelope(dirB, envelope({ seq: 1, payload: { from: 'B' } }));
+ appendFileSync(join(dirA, `room-${room}.jsonl`), JSON.stringify(a1) + '\n');
+ appendFileSync(join(dirB, `room-${room}.jsonl`), JSON.stringify(b1) + '\n');
+
+ const sa = await serveFederation(dirA, { port: 0 }); servers.push(sa.server);
+ const sb = await serveFederation(dirB, { port: 0 }); servers.push(sb.server);
+
+ addPeer(dirA, { nodeId: idB.nodeId, url: `http://127.0.0.1:${sb.port}`, publicKey: idB.publicKey });
+ addPeer(dirB, { nodeId: idA.nodeId, url: `http://127.0.0.1:${sa.port}`, publicKey: idA.publicKey });
+
+ await syncRoomFromPeer(dirA, readPeers(dirA)[0], room);
+ await syncRoomFromPeer(dirB, readPeers(dirB)[0], room);
+
+ const setA = readEnvelopes(dirA, room).map(e => e.envelopeId).sort();
+ const setB = readEnvelopes(dirB, room).map(e => e.envelopeId).sort();
+ expect(setA).toEqual(setB);
+ expect(setA).toHaveLength(2);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/agentbbs-tools.test.ts b/v3/@claude-flow/cli/__tests__/agentbbs-tools.test.ts
index a654b15201..306f8341e8 100644
--- a/v3/@claude-flow/cli/__tests__/agentbbs-tools.test.ts
+++ b/v3/@claude-flow/cli/__tests__/agentbbs-tools.test.ts
@@ -40,14 +40,20 @@ try {
} catch { havePkg = false; }
describe('agentbbs MCP tools β€” structural contract', () => {
- it('exposes exactly 4 tools (register / publish / watch / human_join)', () => {
+ it('exposes the Phase 1 room surface plus the Phase 2 federation surface', () => {
const names = agentbbsTools.map(t => t.name).sort();
- expect(names).toEqual([
- 'federation_bbs_human_join',
- 'federation_bbs_publish',
- 'federation_bbs_register',
- 'federation_bbs_watch',
- ]);
+ // Phase 1 β€” local room/envelope handling.
+ for (const n of ['federation_bbs_register', 'federation_bbs_publish',
+ 'federation_bbs_watch', 'federation_bbs_human_join']) {
+ expect(names).toContain(n);
+ }
+ // Phase 2 β€” cross-host identity, peer pinning, transport and sync.
+ for (const n of ['federation_bbs_identity', 'federation_bbs_peer_add',
+ 'federation_bbs_peers', 'federation_bbs_serve', 'federation_bbs_sync']) {
+ expect(names).toContain(n);
+ }
+ // Pinned so adding a tool is a deliberate contract change, not a slip.
+ expect(names).toHaveLength(9);
});
it('every tool has an object inputSchema with handler + β‰₯80-char description', () => {
diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts
new file mode 100644
index 0000000000..93e776c717
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts
@@ -0,0 +1,477 @@
+/**
+ * agentbbs Phase 2 β€” cross-host federation.
+ *
+ * Phase 1 (`agentbbs-tools.ts`) gives every host an append-only room log at
+ * `<basePath>/room-<roomId>.jsonl`, and derives `roomId` deterministically from
+ * the room label. Two independent hosts that register `#sales` therefore
+ * compute the *same* roomId without ever talking to each other. That is the
+ * property this module builds on.
+ *
+ * ## Why a signed union-merge, and not a consensus protocol
+ *
+ * A room log is an append-only set of immutable envelopes. Two hosts that each
+ * append locally hold two subsets of the same logical set, so reconciling them
+ * is a set union β€” there is no conflicting write to arbitrate, and therefore
+ * nothing for a consensus round to decide. Union is commutative, associative
+ * and idempotent, which makes sync order-independent and safe to retry: pulling
+ * the same peer twice, or pulling A-then-B versus B-then-A, converges on the
+ * same log. That is a CRDT (a grow-only set keyed by `envelopeId`), and it is
+ * strictly cheaper and less failure-prone than the Byzantine agreement the
+ * plugin README gestures at.
+ *
+ * What union does *not* give you is authenticity. If any peer can inject an
+ * envelope, the merge faithfully replicates forgeries. So every envelope is
+ * Ed25519-signed by its originating node, and a receiver verifies the signature
+ * against the *pinned* public key it recorded when the peer was added β€” not
+ * against a key carried in the envelope, which would let an attacker sign with
+ * their own key and claim any origin. Trust is pinned at peer-add time; the
+ * wire is treated as hostile.
+ *
+ * ## Transport
+ *
+ * Pull-based HTTP. A node serves `GET /agentbbs/v1/rooms/:roomId/envelopes?since=N`
+ * and peers poll it. Pull is deliberate: it needs no inbound connectivity from
+ * the peer's side, survives a node being offline (it just catches up later),
+ * and gives the *receiver* control over how much it ingests. Push would invert
+ * that and make every node an unauthenticated write target.
+ *
+ * Designed for a private overlay (Tailscale/WireGuard) where the network
+ * already authenticates the host. Signatures mean a compromised or hostile peer
+ * still cannot forge another node's envelopes. See `bindHost` on serve() β€” it
+ * binds loopback by default, and binding a routable interface is an explicit
+ * operator choice.
+ *
+ * ## Bounds
+ *
+ * Every ingest path is bounded: envelope count per sync, byte size per envelope,
+ * total bytes per response, peer count, and hop count. An unbounded merge from
+ * an untrusted peer is a memory-exhaustion primitive, so limits are enforced on
+ * the *receiving* side where they cannot be negotiated away by the sender.
+ *
+ * @module @claude-flow/cli/mcp-tools/agentbbs-federation
+ */
+
+import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, chmodSync } from 'node:fs';
+import { join } from 'node:path';
+import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
+import { createServer, type Server, type IncomingMessage, type ServerResponse } from 'node:http';
+
+/** Max envelopes accepted from one peer in one sync. */
+export const MAX_ENVELOPES_PER_SYNC = 5_000;
+/** Max serialized bytes for a single envelope. */
+export const MAX_ENVELOPE_BYTES = 64 * 1024;
+/** Max total bytes read from one peer response. */
+export const MAX_SYNC_RESPONSE_BYTES = 16 * 1024 * 1024;
+/** Max peers in the registry. */
+export const MAX_PEERS = 256;
+/** Max federation hops before an envelope stops propagating. */
+export const MAX_HOPS = 8;
+/** Per-request timeout when pulling from a peer. */
+export const SYNC_TIMEOUT_MS = 15_000;
+
+const ROOM_ID_RE = /^[A-Za-z0-9_.\-:/@#]+$/;
+const NODE_ID_RE = /^[0-9a-f]{16}$/;
+const HEX64_RE = /^[0-9a-f]{64}$/;
+
+export interface NodeIdentity {
+ nodeId: string;
+ publicKey: string; // hex
+ privateKey: string; // hex β€” never leaves this host
+ createdAt: string;
+}
+
+export interface FederationPeer {
+ nodeId: string;
+ url: string;
+ publicKey: string; // hex, pinned at add time
+ label?: string;
+ addedAt: string;
+ lastSyncedAt?: string;
+ lastSeq?: Record<string, number>;
+}
+
+export interface SignedEnvelope {
+ envelopeId: string;
+ roomId: string;
+ seq: number;
+ msgType: string;
+ payload: unknown;
+ timestamp: string;
+ origin?: string; // nodeId that created it
+ hops?: number;
+ signature?: string; // hex Ed25519 over canonical()
+}
+
+let _edMod: any = null;
+async function loadEd25519(): Promise<any> {
+ if (!_edMod) _edMod = await import('@noble/ed25519');
+ return _edMod;
+}
+
+function ensureDir(dir: string): void {
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
+}
+
+function hex(buf: Uint8Array): string {
+ return Buffer.from(buf).toString('hex');
+}
+
+function unhex(s: string): Uint8Array {
+ return new Uint8Array(Buffer.from(s, 'hex'));
+}
+
+/**
+ * Deterministic byte string an envelope's signature covers.
+ *
+ * Field order is fixed here rather than relying on `JSON.stringify` key order,
+ * because a receiver must reconstruct byte-identical input from a payload that
+ * survived a JSON round trip. `payload` is canonicalized recursively with
+ * sorted keys for the same reason: `{a:1,b:2}` and `{b:2,a:1}` are the same
+ * value and must not produce different signatures.
+ *
+ * `hops` is deliberately excluded β€” it is mutated in transit by design, so
+ * including it would invalidate the signature at the first relay.
+ */
+export function canonicalEnvelopeBytes(env: SignedEnvelope): Uint8Array {
+ const canon = (v: unknown): unknown => {
+ if (v === null || typeof v !== 'object') return v;
+ if (Array.isArray(v)) return v.map(canon);
+ const out: Record<string, unknown> = {};
+ for (const k of Object.keys(v as Record<string, unknown>).sort()) {
+ out[k] = canon((v as Record<string, unknown>)[k]);
+ }
+ return out;
+ };
+ const material = JSON.stringify({
+ envelopeId: env.envelopeId,
+ roomId: env.roomId,
+ seq: env.seq,
+ msgType: env.msgType,
+ timestamp: env.timestamp,
+ origin: env.origin ?? '',
+ payload: canon(env.payload),
+ });
+ return new TextEncoder().encode(material);
+}
+
+function identityPath(basePath: string): string {
+ return join(basePath, 'node-identity.json');
+}
+
+function peersPath(basePath: string): string {
+ return join(basePath, 'peers.json');
+}
+
+function roomLogPath(basePath: string, roomId: string): string {
+ return join(basePath, `room-${roomId}.jsonl`);
+}
+
+/**
+ * Load or create this host's long-lived Ed25519 identity.
+ *
+ * Phase 1 minted an ephemeral key per process, which is fine for local token
+ * signing but useless across hosts: a peer cannot pin a key that changes on
+ * every restart. This persists one, 0600, and derives a stable nodeId from the
+ * public key so identity is verifiable rather than self-asserted.
+ */
+export async function getNodeIdentity(basePath: string): Promise<NodeIdentity> {
+ ensureDir(basePath);
+ const p = identityPath(basePath);
+ if (existsSync(p)) {
+ const parsed = JSON.parse(readFileSync(p, 'utf-8')) as NodeIdentity;
+ if (!NODE_ID_RE.test(parsed.nodeId ?? '') || !HEX64_RE.test(parsed.publicKey ?? '')) {
+ throw new Error('node-identity.json is malformed');
+ }
+ return parsed;
+ }
+ const ed = await loadEd25519();
+ const priv: Uint8Array = ed.utils?.randomPrivateKey ? ed.utils.randomPrivateKey() : new Uint8Array(randomBytes(32));
+ const pub: Uint8Array = await (ed.getPublicKeyAsync ?? ed.getPublicKey)(priv);
+ const publicKey = hex(pub);
+ const identity: NodeIdentity = {
+ nodeId: createHash('sha256').update(`agentbbs:node:${publicKey}`).digest('hex').slice(0, 16),
+ publicKey,
+ privateKey: hex(priv),
+ createdAt: new Date().toISOString(),
+ };
+ writeFileSync(p, JSON.stringify(identity, null, 2) + '\n', { mode: 0o600 });
+ try { chmodSync(p, 0o600); } catch { /* best effort on filesystems without modes */ }
+ return identity;
+}
+
+export async function signEnvelope(basePath: string, env: SignedEnvelope): Promise<SignedEnvelope> {
+ const id = await getNodeIdentity(basePath);
+ const ed = await loadEd25519();
+ const withOrigin: SignedEnvelope = { ...env, origin: id.nodeId, hops: env.hops ?? 0 };
+ const sig: Uint8Array = await (ed.signAsync ?? ed.sign)(canonicalEnvelopeBytes(withOrigin), unhex(id.privateKey));
+ return { ...withOrigin, signature: hex(sig) };
+}
+
+/**
+ * Verify an envelope against a public key the caller already trusts.
+ *
+ * The key is passed in rather than read from the envelope on purpose: an
+ * envelope-carried key proves only that the sender holds *a* key, not that they
+ * are who the `origin` field claims. Callers pass the key pinned at peer-add.
+ */
+export async function verifyEnvelope(env: SignedEnvelope, publicKeyHex: string): Promise<boolean> {
+ if (!env.signature || !HEX64_RE.test(publicKeyHex)) return false;
+ if (!/^[0-9a-f]{128}$/.test(env.signature)) return false;
+ try {
+ const ed = await loadEd25519();
+ return await (ed.verifyAsync ?? ed.verify)(unhex(env.signature), canonicalEnvelopeBytes(env), unhex(publicKeyHex));
+ } catch {
+ return false;
+ }
+}
+
+export function readPeers(basePath: string): FederationPeer[] {
+ const p = peersPath(basePath);
+ if (!existsSync(p)) return [];
+ try {
+ const parsed = JSON.parse(readFileSync(p, 'utf-8'));
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+}
+
+function writePeers(basePath: string, peers: FederationPeer[]): void {
+ ensureDir(basePath);
+ writeFileSync(peersPath(basePath), JSON.stringify(peers, null, 2) + '\n');
+}
+
+/**
+ * Reject anything that is not a plain http(s) URL to a host.
+ *
+ * Blocks credentials-in-URL (they would be logged), and non-http schemes such
+ * as `file:` which would turn a peer entry into a local file read.
+ */
+export function validatePeerUrl(raw: string): string {
+ let u: URL;
+ try { u = new URL(raw); } catch { throw new Error('peer url is not a valid URL'); }
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') {
+ throw new Error('peer url must be http or https');
+ }
+ if (u.username || u.password) throw new Error('peer url must not embed credentials');
+ return u.origin;
+}
+
+export function addPeer(
+ basePath: string,
+ input: { nodeId: string; url: string; publicKey: string; label?: string },
+): FederationPeer {
+ if (!NODE_ID_RE.test(input.nodeId ?? '')) throw new Error('nodeId must be 16 lowercase hex chars');
+ if (!HEX64_RE.test(input.publicKey ?? '')) throw new Error('publicKey must be 64 lowercase hex chars');
+ const url = validatePeerUrl(String(input.url));
+
+ const peers = readPeers(basePath);
+ if (peers.length >= MAX_PEERS) throw new Error(`peer registry is full (${MAX_PEERS})`);
+
+ const existing = peers.find(p => p.nodeId === input.nodeId);
+ if (existing) {
+ // Re-pinning a different key for a known nodeId is how a key-substitution
+ // attack would present. Require an explicit remove first.
+ if (existing.publicKey !== input.publicKey) {
+ throw new Error(`nodeId ${input.nodeId} is already pinned to a different publicKey; remove it first`);
+ }
+ existing.url = url;
+ if (input.label) existing.label = input.label;
+ writePeers(basePath, peers);
+ return existing;
+ }
+
+ const peer: FederationPeer = {
+ nodeId: input.nodeId,
+ url,
+ publicKey: input.publicKey,
+ label: input.label,
+ addedAt: new Date().toISOString(),
+ lastSeq: {},
+ };
+ peers.push(peer);
+ writePeers(basePath, peers);
+ return peer;
+}
+
+export function removePeer(basePath: string, nodeId: string): boolean {
+ const peers = readPeers(basePath);
+ const next = peers.filter(p => p.nodeId !== nodeId);
+ if (next.length === peers.length) return false;
+ writePeers(basePath, next);
+ return true;
+}
+
+export function readEnvelopes(basePath: string, roomId: string): SignedEnvelope[] {
+ const p = roomLogPath(basePath, roomId);
+ if (!existsSync(p)) return [];
+ const out: SignedEnvelope[] = [];
+ for (const line of readFileSync(p, 'utf-8').split(/\r?\n/)) {
+ if (!line.trim()) continue;
+ try { out.push(JSON.parse(line)); } catch { /* skip malformed */ }
+ }
+ return out;
+}
+
+export function validateRoomId(roomId: string): string {
+ if (!roomId || typeof roomId !== 'string') throw new Error('roomId is required');
+ if (roomId.length > 128) throw new Error('roomId exceeds 128 chars');
+ // Also blocks path traversal: `.` is allowed but `/` segments cannot form
+ // `..` without tripping the explicit check below.
+ if (!ROOM_ID_RE.test(roomId)) throw new Error('roomId has invalid characters');
+ if (roomId.includes('..')) throw new Error('roomId must not contain ..');
+ return roomId;
+}
+
+export interface MergeResult {
+ merged: number;
+ skippedDuplicate: number;
+ skippedUnverified: number;
+ skippedOversize: number;
+ skippedHopLimit: number;
+}
+
+/**
+ * Union-merge verified envelopes from a peer into the local room log.
+ *
+ * Idempotent: `envelopeId` is the merge key, so replaying the same batch is a
+ * no-op. Anything that fails verification is dropped and counted rather than
+ * quarantined β€” a receiver has no use for an envelope it cannot attribute.
+ */
+export async function mergeEnvelopes(
+ basePath: string,
+ roomId: string,
+ incoming: SignedEnvelope[],
+ peerPublicKey: string,
+): Promise<MergeResult> {
+ validateRoomId(roomId);
+ ensureDir(basePath);
+
+ const result: MergeResult = {
+ merged: 0, skippedDuplicate: 0, skippedUnverified: 0, skippedOversize: 0, skippedHopLimit: 0,
+ };
+
+ const existing = readEnvelopes(basePath, roomId);
+ const seen = new Set(existing.map(e => e.envelopeId));
+ const logPath = roomLogPath(basePath, roomId);
+
+ const batch = incoming.slice(0, MAX_ENVELOPES_PER_SYNC);
+ for (const env of batch) {
+ if (!env || typeof env !== 'object' || typeof env.envelopeId !== 'string') {
+ result.skippedUnverified++; continue;
+ }
+ if (env.roomId !== roomId) { result.skippedUnverified++; continue; }
+ if (seen.has(env.envelopeId)) { result.skippedDuplicate++; continue; }
+ if (JSON.stringify(env).length > MAX_ENVELOPE_BYTES) { result.skippedOversize++; continue; }
+ if ((env.hops ?? 0) >= MAX_HOPS) { result.skippedHopLimit++; continue; }
+ if (!(await verifyEnvelope(env, peerPublicKey))) { result.skippedUnverified++; continue; }
+
+ appendFileSync(logPath, JSON.stringify({ ...env, hops: (env.hops ?? 0) + 1 }) + '\n');
+ seen.add(env.envelopeId);
+ result.merged++;
+ }
+ return result;
+}
+
+/** Pull one room from one peer and merge what verifies. */
+export async function syncRoomFromPeer(
+ basePath: string,
+ peer: FederationPeer,
+ roomId: string,
+ fetchImpl: typeof fetch = fetch,
+): Promise<MergeResult & { peerNodeId: string; roomId: string }> {
+ validateRoomId(roomId);
+ const since = peer.lastSeq?.[roomId] ?? 0;
+ const url = `${peer.url}/agentbbs/v1/rooms/${encodeURIComponent(roomId)}/envelopes?since=${since}`;
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), SYNC_TIMEOUT_MS);
+ let body: any;
+ try {
+ const res = await fetchImpl(url, { signal: controller.signal, headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`peer ${peer.nodeId} returned ${res.status}`);
+ const text = await res.text();
+ if (text.length > MAX_SYNC_RESPONSE_BYTES) throw new Error(`peer ${peer.nodeId} response exceeds size cap`);
+ body = JSON.parse(text);
+ } finally {
+ clearTimeout(timer);
+ }
+
+ const envelopes: SignedEnvelope[] = Array.isArray(body?.envelopes) ? body.envelopes : [];
+ const merged = await mergeEnvelopes(basePath, roomId, envelopes, peer.publicKey);
+
+ const peers = readPeers(basePath);
+ const rec = peers.find(p => p.nodeId === peer.nodeId);
+ if (rec) {
+ rec.lastSyncedAt = new Date().toISOString();
+ rec.lastSeq = rec.lastSeq ?? {};
+ const maxSeq = envelopes.reduce((m, e) => Math.max(m, Number(e.seq) || 0), since);
+ rec.lastSeq[roomId] = maxSeq;
+ writePeers(basePath, peers);
+ }
+ return { ...merged, peerNodeId: peer.nodeId, roomId };
+}
+
+/**
+ * Serve this node's room logs for peers to pull.
+ *
+ * Binds loopback unless the caller explicitly asks otherwise, so starting a
+ * server never silently exposes room contents on a routable interface. Read
+ * only by construction: there is no route that mutates state, which removes the
+ * whole class of unauthenticated-write attacks that a push design would open.
+ */
+export function serveFederation(
+ basePath: string,
+ opts: { port?: number; bindHost?: string } = {},
+): Promise<{ server: Server; port: number; host: string }> {
+ const host = opts.bindHost ?? '127.0.0.1';
+ const server = createServer((req: IncomingMessage, res: ServerResponse) => {
+ const send = (code: number, obj: unknown) => {
+ const buf = Buffer.from(JSON.stringify(obj));
+ res.writeHead(code, { 'content-type': 'application/json', 'content-length': buf.length });
+ res.end(buf);
+ };
+ try {
+ if (req.method !== 'GET') return send(405, { error: 'method-not-allowed' });
+ const u = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
+
+ if (u.pathname === '/agentbbs/v1/identity') {
+ const p = identityPath(basePath);
+ if (!existsSync(p)) return send(404, { error: 'no-identity' });
+ const id = JSON.parse(readFileSync(p, 'utf-8')) as NodeIdentity;
+ // Never serve privateKey.
+ return send(200, { nodeId: id.nodeId, publicKey: id.publicKey, createdAt: id.createdAt });
+ }
+
+ const m = u.pathname.match(/^\/agentbbs\/v1\/rooms\/([^/]+)\/envelopes$/);
+ if (m) {
+ let roomId: string;
+ try { roomId = validateRoomId(decodeURIComponent(m[1])); }
+ catch (e) { return send(400, { error: (e as Error).message }); }
+ const since = Math.max(0, Math.trunc(Number(u.searchParams.get('since') ?? 0)) || 0);
+ const all = readEnvelopes(basePath, roomId);
+ const out = all.filter(e => (Number(e.seq) || 0) > since).slice(0, MAX_ENVELOPES_PER_SYNC);
+ return send(200, { roomId, since, count: out.length, envelopes: out });
+ }
+ return send(404, { error: 'not-found' });
+ } catch (e) {
+ return send(500, { error: 'internal' });
+ }
+ });
+
+ return new Promise((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(opts.port ?? 0, host, () => {
+ const addr = server.address();
+ const port = typeof addr === 'object' && addr ? addr.port : 0;
+ resolve({ server, port, host });
+ });
+ });
+}
+
+/** Constant-time compare for any future shared-secret paths. */
+export function safeEqual(a: string, b: string): boolean {
+ const ab = Buffer.from(a); const bb = Buffer.from(b);
+ if (ab.length !== bb.length) return false;
+ return timingSafeEqual(ab, bb);
+}
diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.ts
index b7ff0e336f..474e6a0fa9 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.ts
@@ -40,6 +40,18 @@ import { resolve, isAbsolute, join } from 'node:path';
import { randomBytes, createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import type { MCPTool } from './types.js';
+import {
+ getNodeIdentity,
+ signEnvelope,
+ addPeer,
+ removePeer,
+ readPeers,
+ syncRoomFromPeer,
+ serveFederation,
+ validateRoomId as fedValidateRoomId,
+ MAX_PEERS,
+ MAX_HOPS,
+} from './agentbbs-federation.js';
import { getProjectCwd } from './types.js';
const CLI_NAME = 'agentbbs';
@@ -310,15 +322,20 @@ export const agentbbsTools: MCPTool[] = [
ensureDir(basePath);
const logPath = roomLogPath(basePath, roomId);
- const env: BbsEnvelope = {
+ const base: BbsEnvelope = {
envelopeId: base64url(randomBytes(12)),
roomId,
seq: nextSeq(logPath),
msgType,
payload: input.payload,
timestamp: new Date().toISOString(),
- signature: input.signature ? String(input.signature) : undefined,
};
+ // Phase 2: sign with this host's persistent node identity so peers can
+ // attribute and verify the envelope after a cross-host merge. An
+ // explicitly supplied signature is preserved rather than overwritten.
+ const env: BbsEnvelope = input.signature
+ ? { ...base, signature: String(input.signature) }
+ : (await signEnvelope(basePath, base as any)) as any;
appendFileSync(logPath, JSON.stringify(env) + '\n');
// Phase 1: recipientHopCount is always 0 (single-node). Phase 4+ will
@@ -446,4 +463,133 @@ export const agentbbsTools: MCPTool[] = [
};
},
},
+
+ // ---------------------------------------------------------------- Phase 2
+ {
+ name: 'federation_bbs_identity',
+ description: "agentbbs Phase 2 β€” return this host's persistent federation node identity (nodeId + Ed25519 public key), creating it on first call. Give the nodeId and publicKey to a peer so they can pin you with federation_bbs_peer_add. The private key never leaves this host and is never returned. Use when you are bootstrapping a new host into the federation and a peer needs something to pin. Reading node-identity.json directly is wrong because it also holds the private key, and the file is created lazily so it may not exist yet.",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ basePath: { type: 'string', description: 'Override the .agentbbs directory.' },
+ },
+ },
+ handler: async (input) => {
+ const basePath = resolveBasePath(input.basePath as string | undefined);
+ if (!agentbbsCliAvailable()) return degradedResult('agentbbs-not-found');
+ const id = await getNodeIdentity(basePath);
+ return { success: true, nodeId: id.nodeId, publicKey: id.publicKey, createdAt: id.createdAt };
+ },
+ },
+ {
+ name: 'federation_bbs_peer_add',
+ description: `agentbbs Phase 2 β€” pin a remote federation peer by nodeId, URL and Ed25519 public key. The key is pinned at add time and every envelope merged from this peer is verified against it, so a hostile peer cannot forge another node's envelopes. Re-adding a known nodeId with a different key is refused; remove it first. Max ${MAX_PEERS} peers. Use when you have a peer's identity out of band and want to start syncing with it. Trusting a key carried inside an incoming envelope is wrong because that only proves the sender holds some key, not that they are the node they claim to be.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ nodeId: { type: 'string', description: "Peer's 16-hex nodeId from its federation_bbs_identity." },
+ url: { type: 'string', description: 'Peer base URL, e.g. http://100.104.125.72:7777' },
+ publicKey: { type: 'string', description: "Peer's 64-hex Ed25519 public key." },
+ label: { type: 'string', description: 'Optional human label.' },
+ basePath: { type: 'string' },
+ },
+ required: ['nodeId', 'url', 'publicKey'],
+ },
+ handler: async (input) => {
+ const basePath = resolveBasePath(input.basePath as string | undefined);
+ if (!agentbbsCliAvailable()) return degradedResult('agentbbs-not-found');
+ const peer = addPeer(basePath, {
+ nodeId: String(input.nodeId),
+ url: String(input.url),
+ publicKey: String(input.publicKey),
+ label: input.label ? String(input.label) : undefined,
+ });
+ return { success: true, peer: { nodeId: peer.nodeId, url: peer.url, label: peer.label, addedAt: peer.addedAt } };
+ },
+ },
+ {
+ name: 'federation_bbs_peers',
+ description: 'agentbbs Phase 2 β€” list pinned federation peers with last-sync state. Public keys are returned so an operator can compare a pin against what the peer reports; private material is never included. Use when you want to audit who this host will accept envelopes from, or unpin a peer. Editing peers.json by hand is wrong because a malformed entry silently disables verification for that peer on the next sync.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ remove: { type: 'string', description: 'Optional nodeId to unpin instead of listing.' },
+ basePath: { type: 'string' },
+ },
+ },
+ handler: async (input) => {
+ const basePath = resolveBasePath(input.basePath as string | undefined);
+ if (!agentbbsCliAvailable()) return degradedResult('agentbbs-not-found');
+ if (input.remove) {
+ const removed = removePeer(basePath, String(input.remove));
+ return { success: true, removed, nodeId: String(input.remove) };
+ }
+ return { success: true, peers: readPeers(basePath) };
+ },
+ },
+ {
+ name: 'federation_bbs_serve',
+ description: 'agentbbs Phase 2 β€” start the read-only pull endpoint peers fetch from (GET /agentbbs/v1/rooms/:roomId/envelopes). Binds 127.0.0.1 unless bindHost is given explicitly, so room contents are never exposed on a routable interface by accident. There is no route that mutates state. Use when this host needs to be reachable by peers that pull from it. Exposing the .agentbbs directory over a static file server is wrong because that would serve node-identity.json, which contains the private key.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ port: { type: 'number', description: 'Port to listen on. 0 picks a free one.' },
+ bindHost: { type: 'string', description: 'Interface to bind. Defaults to 127.0.0.1; set a tailnet IP to federate.' },
+ basePath: { type: 'string' },
+ },
+ },
+ handler: async (input) => {
+ const basePath = resolveBasePath(input.basePath as string | undefined);
+ if (!agentbbsCliAvailable()) return degradedResult('agentbbs-not-found');
+ const { port, host } = await serveFederation(basePath, {
+ port: typeof input.port === 'number' ? input.port : undefined,
+ bindHost: input.bindHost ? String(input.bindHost) : undefined,
+ });
+ const id = await getNodeIdentity(basePath);
+ return { success: true, listening: `http://${host}:${port}`, nodeId: id.nodeId, publicKey: id.publicKey };
+ },
+ },
+ {
+ name: 'federation_bbs_sync',
+ description: `agentbbs Phase 2 β€” pull a room from pinned peers and union-merge what verifies. Merge is keyed on envelopeId so it is idempotent and order-independent; unsigned, misattributed, oversize and over-hop (>${MAX_HOPS}) envelopes are dropped and counted rather than merged. Use after publish to propagate, or on a timer to converge. Use when you want to converge this host's rooms with its peers, on demand or on a timer. Copying room-*.jsonl between machines is wrong because it bypasses signature verification, dedupe and the hop limit, so a single hostile or looping file can corrupt the log.`,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ roomId: { type: 'string', description: 'Room to sync. Same label yields the same roomId on every host.' },
+ nodeId: { type: 'string', description: 'Optional single peer to sync from; default is all pinned peers.' },
+ basePath: { type: 'string' },
+ },
+ required: ['roomId'],
+ },
+ handler: async (input) => {
+ const basePath = resolveBasePath(input.basePath as string | undefined);
+ const roomId = fedValidateRoomId(String(input.roomId));
+ if (!agentbbsCliAvailable()) return degradedResult('agentbbs-not-found');
+
+ const all = readPeers(basePath);
+ const targets = input.nodeId ? all.filter(p => p.nodeId === String(input.nodeId)) : all;
+ if (targets.length === 0) return { success: true, roomId, peersSynced: 0, results: [], note: 'no pinned peers' };
+
+ type SyncRow = { peerNodeId: string; roomId: string; merged: number; skippedDuplicate: number;
+ skippedUnverified: number; skippedOversize: number; skippedHopLimit: number; error?: string };
+ const results: SyncRow[] = [];
+ for (const peer of targets) {
+ try {
+ results.push(await syncRoomFromPeer(basePath, peer, roomId));
+ } catch (e) {
+ // One unreachable peer must not fail the whole sync β€” the merge is
+ // idempotent, so this peer simply catches up on the next run.
+ results.push({ peerNodeId: peer.nodeId, roomId, error: (e as Error).message,
+ merged: 0, skippedDuplicate: 0, skippedUnverified: 0, skippedOversize: 0, skippedHopLimit: 0 });
+ }
+ }
+ return {
+ success: true,
+ roomId,
+ peersSynced: results.length,
+ totalMerged: results.reduce((n, r) => n + (r.merged || 0), 0),
+ results,
+ };
+ },
+ },
];