diff --git a/build.zig b/build.zig index 99ebde6..440443a 100644 --- a/build.zig +++ b/build.zig @@ -649,6 +649,28 @@ pub fn build(b: *std.Build) void { const run_a2a_conversation_step = b.step("run-a2a-conversation", "Run autonomous A2A conversation between two agents"); run_a2a_conversation_step.dependOn(&run_a2a_conversation.step); + // A2A Swarm Agent (DHT-based agent discovery + A2A messaging) + const swarm_agent_module = b.createModule(.{ + .root_source_file = b.path("examples/a2a/swarm_agent.zig"), + .target = target, + .optimize = optimize, + }); + swarm_agent_module.addImport("p2p", p2p_module); + swarm_agent_module.addImport("network", network_module); + swarm_agent_module.addImport("protocol", a2a_protocol_module); + + const swarm_agent = b.addExecutable(.{ + .name = "swarm-agent", + .root_module = swarm_agent_module, + }); + b.installArtifact(swarm_agent); + + const run_swarm_agent = b.addRunArtifact(swarm_agent); + run_swarm_agent.step.dependOn(b.getInstallStep()); + if (b.args) |args| run_swarm_agent.addArgs(args); + const run_swarm_agent_step = b.step("run-swarm-agent", "Run DHT-based A2A swarm agent"); + run_swarm_agent_step.dependOn(&run_swarm_agent.step); + // Resume test const resume_test_module = b.createModule(.{ .root_source_file = b.path("examples/resume_test.zig"), diff --git a/docs/A2A_SWARM_GUIDE.md b/docs/A2A_SWARM_GUIDE.md new file mode 100644 index 0000000..8147eca --- /dev/null +++ b/docs/A2A_SWARM_GUIDE.md @@ -0,0 +1,206 @@ +# A2A Swarm Agent Guide + +Run a multi-agent LLM swarm where agents discover each other via the DHT and communicate using the A2A protocol. No central server required beyond a bootstrap node. + +## Architecture + +``` + DHT Network + ┌────────────┐ + ┌─────────────│ Topic Key │─────────────┐ + │ └────────────┘ │ + │ dhtStore() │ dhtFindValue() │ + │ │ │ +┌────▼────┐ ┌─────▼─────┐ ┌─────▼───┐ +│ Agent A │◄──────►│ Bootstrap │◄──────►│ Agent B │ +│ llama3 │ A2A │ (seed) │ A2A │ mistral │ +└─────────┘ msgs └───────────┘ msgs └─────────┘ + port 9001 port 9000 port 9002 +``` + +**How it works:** + +1. A bootstrap agent starts and prints its DHT node ID +2. Other agents join the swarm by connecting to the bootstrap node +3. Each agent advertises itself on the DHT under a topic key (`blake2b("a2a-topic:" + topic)`) +4. Agents discover each other by querying the DHT for that topic key +5. Agents exchange A2A chat messages over the P2P network + +## Prerequisites + +- [Zig](https://ziglang.org/download/) (0.15+) +- [Ollama](https://ollama.ai/) running on each machine (or a shared endpoint) +- A model pulled: `ollama pull llama3.2` + +## Setup + +### 1. Build on each server + +```bash +zig build +``` + +Or cross-compile for Linux and copy the binary: + +```bash +zig build -Doptimize=ReleaseFast -Dtarget=x86_64-linux +scp zig-out/bin/swarm-agent user@server:/usr/local/bin/ +``` + +### 2. Install Ollama on each server + +```bash +curl -fsSL https://ollama.ai/install.sh | sh +ollama pull llama3.2 +``` + +### 3. Ensure the P2P port (default 9000) is open + +```bash +# Example: UFW +sudo ufw allow 9000/udp +sudo ufw allow 9000/tcp +``` + +## Deployment + +### Server A — Bootstrap node (203.0.113.10) + +```bash +swarm-agent \ + --name bootstrap \ + --port 9000 \ + --public-ip 203.0.113.10 \ + --model llama3.2 +``` + +Output: +``` +=== A2A Swarm Agent === +Name: bootstrap +Port: 9000 +Model: llama3.2 +Topic: a2a-swarm +DHT ID: a1b2c3d4e5f6... <-- copy this value + +Other agents can join with: + --bootstrap 203.0.113.10:9000 --dht-id a1b2c3d4e5f6... +``` + +Copy the 64-character DHT ID — every other server needs it. + +### Server B — Agent (198.51.100.20) + +```bash +swarm-agent \ + --name server-b \ + --port 9000 \ + --public-ip 198.51.100.20 \ + --model mistral \ + --bootstrap 203.0.113.10:9000 \ + --dht-id +``` + +### Server C — Agent (192.0.2.30) + +```bash +swarm-agent \ + --name server-c \ + --port 9000 \ + --public-ip 192.0.2.30 \ + --model llama3.2 \ + --bootstrap 203.0.113.10:9000 \ + --dht-id +``` + +### Query from any machine + +Send a one-shot question to the first discovered agent and exit: + +```bash +swarm-agent \ + --name client \ + --port 9003 \ + --public-ip 10.0.0.50 \ + --bootstrap 203.0.113.10:9000 \ + --dht-id \ + --ask "What is quantum computing?" +``` + +## CLI Reference + +``` +swarm-agent [options] + +Options: + --name Agent name (default: agent) + --port P2P listen port (default: 9000) + --model LLM model name (default: llama3.2) + --ollama-url Ollama endpoint (default: http://localhost:11434) + --bootstrap Bootstrap node address + --dht-id Bootstrap node's DHT node ID (64 hex chars) + --public-ip Explicit public IP for NAT environments + --topic Agent topic to advertise (default: a2a-swarm) + --ask Send message to first discovered agent and exit + --help, -h Show this help +``` + +## Agent Discovery via DHT + +Each agent advertises a JSON payload on the DHT: + +```json +{ + "name": "alice", + "port": 9001, + "ip": "203.0.113.10", + "model": "llama3.2", + "capability": "chat" +} +``` + +The DHT key is derived from the topic name: + +``` +key = blake2b("a2a-topic:" + topic_name) // 32 bytes +``` + +All agents using the same `--topic` value will share the same DHT key. The DHT entry has a TTL of 300 seconds and is re-advertised every 60 seconds. + +## A2A Message Format + +Messages use the existing A2A wire protocol (`examples/a2a/protocol.zig`): + +- **Request** (type `0x01`): JSON with `request_id`, `model`, `messages[]`, `temperature`, `capability` +- **Response** (type `0x02`): JSON with `request_id`, `success`, `content`, `model`, `agent_id` + +Messages are sent as P2P messages with protocol ID `0x42`. + +## NAT Traversal + +The swarm agent supports several address discovery methods (in priority order): + +1. `--public-ip` flag (explicit, recommended for cloud servers) +2. IP Reflection / Bundled STUN (learned from DHT peers automatically) +3. Localhost fallback (for local testing) + +For servers behind NAT, always use `--public-ip` with the server's public IP and ensure the listen port is forwarded. + +## Scaling to N Agents + +- All agents bootstrap to the same node (or any existing swarm member) +- Each agent advertises on the same topic key +- The DHT propagates entries across the network +- DHT entries are refreshed every 60 seconds +- Current DHT stores a single value per key (last-writer-wins); for multi-agent discovery, use distinct topics or connect via the bootstrap peer list + +## Troubleshooting + +| Symptom | Fix | +|---------|-----| +| "No agents discovered" | Ensure `--dht-id` matches the bootstrap node's printed DHT ID | +| "Failed to connect to bootstrap" | Check firewall/port forwarding; ensure bootstrap is running | +| "LLM call failed" | Verify Ollama is running: `curl http://localhost:11434/api/tags` | +| "Timeout" waiting for response | The responding agent may be slow (large model) — increase timeout or use a smaller model | +| Agent not found via DHT | Wait a few seconds for DHT propagation; try `--ask` again | +| Wrong IP advertised | Use `--public-ip` to set the correct reachable address | diff --git a/examples/a2a/swarm_agent.zig b/examples/a2a/swarm_agent.zig new file mode 100644 index 0000000..caf2be4 --- /dev/null +++ b/examples/a2a/swarm_agent.zig @@ -0,0 +1,733 @@ +//! A2A Swarm Agent - DHT-based agent discovery + A2A messaging +//! +//! Combines DHT-based peer discovery (from mwp_demo pattern) with the a2a +//! messaging protocol. Agents join a swarm via a bootstrap node and discover +//! each other through the DHT using topic keys. +//! +//! Usage: +//! # Bootstrap node (first agent): +//! zig build run-swarm-agent -- --name bootstrap --port 9000 +//! +//! # Join swarm and discover agents: +//! zig build run-swarm-agent -- --name alice --port 9001 \ +//! --bootstrap 127.0.0.1:9000 --dht-id +//! +//! # Join and ask a question: +//! zig build run-swarm-agent -- --name bob --port 9002 \ +//! --bootstrap 127.0.0.1:9000 --dht-id \ +//! --ask "What is the meaning of life?" + +const std = @import("std"); +const http = std.http; +const p2p_lib = @import("p2p"); +const network = @import("network"); +const protocol = @import("protocol"); + +const P2P = p2p_lib.P2P; +const P2PConfig = p2p_lib.P2PConfig; +const PeerId = network.PeerId; +const Address = p2p_lib.Address; + +const SwarmConfig = struct { + name: []const u8 = "agent", + listen_port: u16 = 9000, + ollama_url: []const u8 = "http://localhost:11434", + model: []const u8 = "llama3.2", + capability: []const u8 = "chat", + bootstrap_addr: ?[]const u8 = null, + bootstrap_dht_id: ?[32]u8 = null, + public_ip: ?[4]u8 = null, + topic: []const u8 = "a2a-swarm", + ask_message: ?[]const u8 = null, +}; + +const SwarmAgent = struct { + allocator: std.mem.Allocator, + config: SwarmConfig, + p2p_instance: P2P, + running: std.atomic.Value(bool), + http_client: http.Client, + connected_peers: std.ArrayList(PeerId), + pending_responses: std.AutoHashMap([16]u8, []const u8), + mutex: std.Thread.Mutex, + + pub fn init(allocator: std.mem.Allocator, cfg: SwarmConfig) !SwarmAgent { + var p2p_config = P2PConfig{}; + p2p_config.network.listen_port = cfg.listen_port; + p2p_config.network.enable_noise_encryption = true; + p2p_config.network.enable_dos_protection = false; + + return .{ + .allocator = allocator, + .config = cfg, + .p2p_instance = try P2P.init(allocator, p2p_config), + .running = std.atomic.Value(bool).init(false), + .http_client = http.Client{ .allocator = allocator }, + .connected_peers = .{}, + .pending_responses = std.AutoHashMap([16]u8, []const u8).init(allocator), + .mutex = .{}, + }; + } + + pub fn deinit(self: *SwarmAgent) void { + self.stop(); + self.http_client.deinit(); + self.connected_peers.deinit(self.allocator); + + var it = self.pending_responses.valueIterator(); + while (it.next()) |v| { + self.allocator.free(v.*); + } + self.pending_responses.deinit(); + + self.p2p_instance.deinit(); + } + + pub fn start(self: *SwarmAgent) !void { + try self.p2p_instance.start(); + + // Listen on 0.0.0.0 to accept from all interfaces + const listen_addr = Address.ipv4(.{ 0, 0, 0, 0 }, self.config.listen_port); + try self.p2p_instance.startListening(listen_addr); + + self.running.store(true, .release); + + // Get our DHT node ID + const local_dht_id = self.p2p_instance.getDhtLocalId() orelse { + std.debug.print("ERROR: No DHT ID available\n", .{}); + return error.DhtNotInitialized; + }; + var dht_id_hex: [64]u8 = undefined; + _ = formatHex(&local_dht_id, &dht_id_hex); + + std.debug.print("\n=== A2A Swarm Agent ===\n", .{}); + std.debug.print("Name: {s}\n", .{self.config.name}); + std.debug.print("Port: {d}\n", .{self.config.listen_port}); + std.debug.print("Model: {s}\n", .{self.config.model}); + std.debug.print("Topic: {s}\n", .{self.config.topic}); + std.debug.print("Ollama: {s}\n", .{self.config.ollama_url}); + std.debug.print("DHT ID: {s}\n\n", .{dht_id_hex}); + + // Bootstrap if address provided + if (self.config.bootstrap_addr) |addr_str| { + std.debug.print("Connecting to bootstrap node: {s}...\n", .{addr_str}); + const peer_id = try self.connectToPeer(addr_str); + std.debug.print("Connected to bootstrap peer: {x}\n", .{peer_id.bytes[0..8].*}); + + // Register DHT node ID mapping + if (self.config.bootstrap_dht_id) |remote_dht_id| { + std.debug.print("Registering DHT peer mapping...\n", .{}); + try self.p2p_instance.registerDhtNodeId(remote_dht_id, peer_id); + + // Parse bootstrap address for dhtAddPeer + const boot_addr = try parseAddress(addr_str); + self.p2p_instance.dhtAddPeer(remote_dht_id, boot_addr) catch |err| { + std.debug.print("Warning: Failed to add DHT peer: {}\n", .{err}); + }; + std.debug.print("DHT peer registered!\n", .{}); + } + + // Trigger DHT query for IP reflection + std.debug.print("Discovering network address via IP reflection...\n", .{}); + const dummy_key: [32]u8 = [_]u8{0xDE, 0xAD, 0xBE, 0xEF} ++ [_]u8{0} ** 28; + _ = self.p2p_instance.dhtFindValue(dummy_key) catch {}; + + // Process messages to receive DHT response + for (0..30) |_| { + try self.p2p_instance.update(); + std.Thread.sleep(50 * std.time.ns_per_ms); + } + + // Report discovered address + if (self.p2p_instance.getObservedPublicAddress()) |observed| { + switch (observed.ip) { + .v4 => |ip| std.debug.print("Discovered public address: {d}.{d}.{d}.{d}:{d}\n", .{ ip[0], ip[1], ip[2], ip[3], observed.port }), + .v6 => std.debug.print("Discovered public IPv6 address (port {d})\n", .{observed.port}), + } + } + } + + // Advertise this agent on the DHT + try self.advertiseAgent(); + + std.debug.print("\nOther agents can join with:\n", .{}); + std.debug.print(" --bootstrap 127.0.0.1:{d} --dht-id {s}\n\n", .{ self.config.listen_port, dht_id_hex }); + } + + pub fn stop(self: *SwarmAgent) void { + self.running.store(false, .release); + self.p2p_instance.stop() catch {}; + } + + /// Derive a 32-byte topic key from a topic name using blake2b + fn topicKey(self: *SwarmAgent) [32]u8 { + var key: [32]u8 = undefined; + var hasher = std.crypto.hash.blake2.Blake2b256.init(.{}); + hasher.update("a2a-topic:"); + hasher.update(self.config.topic); + hasher.final(&key); + return key; + } + + /// Advertise this agent on the DHT under the topic key + fn advertiseAgent(self: *SwarmAgent) !void { + const key = self.topicKey(); + + // Determine our advertised IP + var ip_str_buf: [15]u8 = undefined; + var ip_str_len: usize = 0; + + if (self.config.public_ip) |ip| { + ip_str_len = (std.fmt.bufPrint(&ip_str_buf, "{d}.{d}.{d}.{d}", .{ ip[0], ip[1], ip[2], ip[3] }) catch unreachable).len; + } else if (self.p2p_instance.getObservedPublicAddress()) |observed| { + switch (observed.ip) { + .v4 => |ip| { + ip_str_len = (std.fmt.bufPrint(&ip_str_buf, "{d}.{d}.{d}.{d}", .{ ip[0], ip[1], ip[2], ip[3] }) catch unreachable).len; + }, + .v6 => {}, + } + } + + if (ip_str_len == 0) { + ip_str_len = (std.fmt.bufPrint(&ip_str_buf, "127.0.0.1", .{}) catch unreachable).len; + } + + // Build JSON agent info payload + var payload = std.ArrayList(u8){}; + defer payload.deinit(self.allocator); + + try payload.appendSlice(self.allocator, "{\"name\":\""); + try appendEscaped(self.allocator, &payload, self.config.name); + try payload.appendSlice(self.allocator, "\",\"port\":"); + var port_buf: [5]u8 = undefined; + const port_str = std.fmt.bufPrint(&port_buf, "{d}", .{self.config.listen_port}) catch unreachable; + try payload.appendSlice(self.allocator, port_str); + try payload.appendSlice(self.allocator, ",\"ip\":\""); + try payload.appendSlice(self.allocator, ip_str_buf[0..ip_str_len]); + try payload.appendSlice(self.allocator, "\",\"model\":\""); + try appendEscaped(self.allocator, &payload, self.config.model); + try payload.appendSlice(self.allocator, "\",\"capability\":\""); + try appendEscaped(self.allocator, &payload, self.config.capability); + try payload.appendSlice(self.allocator, "\"}"); + + try self.p2p_instance.dhtStore(key, payload.items, 300); + + var key_hex: [64]u8 = undefined; + _ = formatHex(&key, &key_hex); + std.debug.print("Advertised agent on DHT topic: {s}\n", .{key_hex}); + std.debug.print(" Payload: {s}\n", .{payload.items}); + } + + /// Discover agents by querying the DHT for the topic key + fn discoverAgents(self: *SwarmAgent) !?DiscoveredAgent { + const key = self.topicKey(); + + // Process pending messages first + try self.p2p_instance.update(); + + const result = self.p2p_instance.dhtFindValue(key) catch return null; + if (result) |value| { + defer self.allocator.free(value); + + // Parse the JSON agent info + const parsed = std.json.parseFromSlice( + std.json.Value, + self.allocator, + value, + .{}, + ) catch return null; + defer parsed.deinit(); + + const obj = parsed.value.object; + const agent_name = obj.get("name") orelse return null; + const agent_port = obj.get("port") orelse return null; + const agent_ip = obj.get("ip") orelse return null; + const agent_model = obj.get("model") orelse return null; + + return DiscoveredAgent{ + .name = try self.allocator.dupe(u8, agent_name.string), + .ip = try self.allocator.dupe(u8, agent_ip.string), + .port = @intCast(agent_port.integer), + .model = try self.allocator.dupe(u8, agent_model.string), + }; + } + + return null; + } + + fn connectToPeer(self: *SwarmAgent, addr_str: []const u8) !PeerId { + const addr = try parseAddress(addr_str); + const peer_id = try self.p2p_instance.connectToPeer(addr); + + self.mutex.lock(); + defer self.mutex.unlock(); + try self.connected_peers.append(self.allocator, peer_id); + + return peer_id; + } + + /// Send a chat request to another agent and wait for response + pub fn askAgent(self: *SwarmAgent, peer: PeerId, message: []const u8) ![]const u8 { + const request_id = protocol.generateRequestId(); + + const messages = [_]protocol.ChatMessage{ + .{ .role = .user, .content = message }, + }; + + const request = protocol.A2ARequest{ + .request_id = request_id, + .model = self.config.model, + .messages = &messages, + .temperature = 0.7, + .capability = self.config.capability, + }; + + // Send request + var payload_buf = std.ArrayList(u8){}; + defer payload_buf.deinit(self.allocator); + + try payload_buf.append(self.allocator, @intFromEnum(protocol.MessageType.request)); + const json = try request.toJson(self.allocator); + defer self.allocator.free(json); + try payload_buf.appendSlice(self.allocator, json); + + _ = try self.p2p_instance.sendMessage(peer, 0x42, payload_buf.items); + std.debug.print("Sent request to peer {x}: \"{s}\"\n", .{ peer.bytes[0..8].*, message }); + + // Wait for response (60s timeout) + const timeout_ns: i128 = 60 * std.time.ns_per_s; + const start_time = std.time.nanoTimestamp(); + + while (std.time.nanoTimestamp() - start_time < timeout_ns) { + self.processOnce() catch {}; + + self.mutex.lock(); + if (self.pending_responses.get(request_id)) |response| { + _ = self.pending_responses.remove(request_id); + self.mutex.unlock(); + return response; + } + self.mutex.unlock(); + + std.Thread.sleep(10 * std.time.ns_per_ms); + } + + return error.Timeout; + } + + pub fn getPeers(self: *SwarmAgent) []const PeerId { + self.mutex.lock(); + defer self.mutex.unlock(); + return self.connected_peers.items; + } + + /// Process one iteration of the event loop + pub fn processOnce(self: *SwarmAgent) !void { + try self.p2p_instance.update(); + + while (self.p2p_instance.getNextEvent()) |event| { + defer { + var evt = event; + evt.deinit(); + } + switch (event.data) { + .message_received => |msg| { + self.handleMessage(msg.source, msg.data) catch |err| { + std.debug.print("Message handling error: {}\n", .{err}); + }; + }, + .peer_connected => |conn| { + std.debug.print("Peer connected: {x}\n", .{conn.peer_id.bytes[0..8].*}); + self.mutex.lock(); + self.connected_peers.append(self.allocator, conn.peer_id) catch {}; + self.mutex.unlock(); + }, + .peer_disconnected => |disc| { + std.debug.print("Peer disconnected: {x}\n", .{disc.peer_id.bytes[0..8].*}); + self.mutex.lock(); + for (self.connected_peers.items, 0..) |p, i| { + if (std.mem.eql(u8, &p.bytes, &disc.peer_id.bytes)) { + _ = self.connected_peers.swapRemove(i); + break; + } + } + self.mutex.unlock(); + }, + else => {}, + } + } + } + + /// Run the agent's main loop + pub fn run(self: *SwarmAgent) !void { + std.debug.print("Agent running. Waiting for messages...\n\n", .{}); + + var last_advertise: i64 = std.time.milliTimestamp(); + var last_heartbeat: i64 = std.time.milliTimestamp(); + + while (self.running.load(.acquire)) { + try self.processOnce(); + + const now = std.time.milliTimestamp(); + + // Re-advertise every 60 seconds to keep DHT entry fresh + if (now - last_advertise >= 60_000) { + last_advertise = now; + self.advertiseAgent() catch |err| { + std.debug.print("Re-advertise failed: {}\n", .{err}); + }; + } + + // Heartbeat every 10 seconds + if (now - last_heartbeat >= 10_000) { + last_heartbeat = now; + const dht_count = self.p2p_instance.getDhtPeerCount(); + const peer_count = self.getPeers().len; + std.debug.print("[heartbeat] DHT peers: {d}, connected: {d}\n", .{ dht_count, peer_count }); + } + + std.Thread.sleep(10 * std.time.ns_per_ms); + } + } + + fn handleMessage(self: *SwarmAgent, from_peer: PeerId, data: []const u8) !void { + if (data.len < 2) return; + + const msg_type: protocol.MessageType = @enumFromInt(data[0]); + + switch (msg_type) { + .request => { + const request = try protocol.A2ARequest.fromJson(self.allocator, data[1..]); + defer { + self.allocator.free(request.model); + self.allocator.free(request.capability); + for (request.messages) |msg| { + self.allocator.free(msg.content); + } + self.allocator.free(request.messages); + } + + std.debug.print("\nRequest from {x}: \"{s}\"\n", .{ + from_peer.bytes[0..8].*, + if (request.messages.len > 0) request.messages[request.messages.len - 1].content else "(empty)", + }); + + const response = try self.handleRequest(from_peer, request); + defer self.allocator.free(response.content); + defer self.allocator.free(response.model); + + // Send response back + var response_data = std.ArrayList(u8){}; + defer response_data.deinit(self.allocator); + + try response_data.append(self.allocator, @intFromEnum(protocol.MessageType.response)); + const resp_json = try response.toJson(self.allocator); + defer self.allocator.free(resp_json); + try response_data.appendSlice(self.allocator, resp_json); + + _ = try self.p2p_instance.sendMessage(from_peer, 0x42, response_data.items); + std.debug.print("Sent response to {x}\n\n", .{from_peer.bytes[0..8].*}); + }, + .response => { + const response = try protocol.A2AResponse.fromJson(self.allocator, data[1..]); + defer self.allocator.free(response.model); + + std.debug.print("\nResponse from {x}: \"{s}\"\n\n", .{ + from_peer.bytes[0..8].*, + response.content, + }); + + // Store response for askAgent to pick up + self.mutex.lock(); + self.pending_responses.put(response.request_id, response.content) catch {}; + self.mutex.unlock(); + }, + else => {}, + } + } + + fn handleRequest(self: *SwarmAgent, from_peer: PeerId, request: protocol.A2ARequest) !protocol.A2AResponse { + _ = from_peer; + + const response_content = self.callOllama(request) catch |err| { + std.debug.print("Ollama error: {}\n", .{err}); + return .{ + .request_id = request.request_id, + .success = false, + .content = try self.allocator.dupe(u8, "LLM call failed"), + .error_message = @errorName(err), + .model = try self.allocator.dupe(u8, self.config.model), + .agent_id = if (self.p2p_instance.getLocalPeerId()) |id| id.bytes else [_]u8{0} ** 32, + }; + }; + + return .{ + .request_id = request.request_id, + .success = true, + .content = response_content, + .model = try self.allocator.dupe(u8, self.config.model), + .agent_id = if (self.p2p_instance.getLocalPeerId()) |id| id.bytes else [_]u8{0} ** 32, + }; + } + + fn callOllama(self: *SwarmAgent, request: protocol.A2ARequest) ![]u8 { + var body = std.ArrayList(u8){}; + defer body.deinit(self.allocator); + + try body.appendSlice(self.allocator, "{\"model\":\""); + try body.appendSlice(self.allocator, self.config.model); + try body.appendSlice(self.allocator, "\",\"messages\":["); + + for (request.messages, 0..) |msg, i| { + if (i > 0) try body.append(self.allocator, ','); + try body.appendSlice(self.allocator, "{\"role\":\""); + try body.appendSlice(self.allocator, msg.role.toString()); + try body.appendSlice(self.allocator, "\",\"content\":\""); + try appendEscaped(self.allocator, &body, msg.content); + try body.appendSlice(self.allocator, "\"}"); + } + + try body.appendSlice(self.allocator, "],\"stream\":false}"); + + const url = try std.fmt.allocPrint(self.allocator, "{s}/api/chat", .{self.config.ollama_url}); + defer self.allocator.free(url); + + var response_writer: std.Io.Writer.Allocating = .init(self.allocator); + defer response_writer.deinit(); + + const result = self.http_client.fetch(.{ + .location = .{ .url = url }, + .method = .POST, + .payload = body.items, + .headers = .{ + .content_type = .{ .override = "application/json" }, + }, + .response_writer = &response_writer.writer, + }) catch |err| { + std.debug.print("HTTP error: {}\n", .{err}); + return error.HttpRequestFailed; + }; + + if (result.status != .ok) { + return error.OllamaError; + } + + const response_data = response_writer.written(); + + const parsed = std.json.parseFromSlice( + std.json.Value, + self.allocator, + response_data, + .{}, + ) catch return error.InvalidJson; + defer parsed.deinit(); + + const message = parsed.value.object.get("message") orelse return error.InvalidResponse; + const content = message.object.get("content") orelse return error.InvalidResponse; + + return try self.allocator.dupe(u8, content.string); + } + + const DiscoveredAgent = struct { + name: []const u8, + ip: []const u8, + port: u16, + model: []const u8, + + fn deinit(self: *const DiscoveredAgent, allocator: std.mem.Allocator) void { + allocator.free(self.name); + allocator.free(self.ip); + allocator.free(self.model); + } + }; +}; + +fn parseAddress(addr_str: []const u8) !Address { + var it = std.mem.splitScalar(u8, addr_str, ':'); + const ip_str = it.next() orelse return error.InvalidAddress; + const port_str = it.next() orelse return error.InvalidAddress; + const port = try std.fmt.parseInt(u16, port_str, 10); + + var ip_parts: [4]u8 = undefined; + var ip_it = std.mem.splitScalar(u8, ip_str, '.'); + for (&ip_parts) |*part| { + const part_str = ip_it.next() orelse return error.InvalidAddress; + part.* = try std.fmt.parseInt(u8, part_str, 10); + } + + return Address.ipv4(ip_parts, port); +} + +fn formatHex(bytes: []const u8, buf: []u8) []u8 { + const charset = "0123456789abcdef"; + for (bytes, 0..) |b, i| { + buf[i * 2] = charset[b >> 4]; + buf[i * 2 + 1] = charset[b & 0x0f]; + } + return buf[0 .. bytes.len * 2]; +} + +fn parseHex(hex: []const u8, out: []u8) !void { + if (hex.len != out.len * 2) return error.InvalidLength; + for (0..out.len) |i| { + out[i] = std.fmt.parseInt(u8, hex[i * 2 ..][0..2], 16) catch return error.InvalidHex; + } +} + +fn appendEscaped(allocator: std.mem.Allocator, list: *std.ArrayList(u8), s: []const u8) !void { + for (s) |c| { + switch (c) { + '"' => try list.appendSlice(allocator, "\\\""), + '\\' => try list.appendSlice(allocator, "\\\\"), + '\n' => try list.appendSlice(allocator, "\\n"), + '\r' => try list.appendSlice(allocator, "\\r"), + '\t' => try list.appendSlice(allocator, "\\t"), + else => try list.append(allocator, c), + } + } +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var cfg = SwarmConfig{}; + var args = try std.process.argsWithAllocator(allocator); + defer args.deinit(); + + _ = args.skip(); + + while (args.next()) |arg| { + if (std.mem.eql(u8, arg, "--name")) { + if (args.next()) |v| cfg.name = v; + } else if (std.mem.eql(u8, arg, "--port")) { + if (args.next()) |v| cfg.listen_port = try std.fmt.parseInt(u16, v, 10); + } else if (std.mem.eql(u8, arg, "--model")) { + if (args.next()) |v| cfg.model = v; + } else if (std.mem.eql(u8, arg, "--ollama-url")) { + if (args.next()) |v| cfg.ollama_url = v; + } else if (std.mem.eql(u8, arg, "--bootstrap")) { + cfg.bootstrap_addr = args.next(); + } else if (std.mem.eql(u8, arg, "--dht-id")) { + const hex = args.next() orelse return error.MissingArg; + cfg.bootstrap_dht_id = [_]u8{0} ** 32; + try parseHex(hex, &cfg.bootstrap_dht_id.?); + } else if (std.mem.eql(u8, arg, "--public-ip")) { + const ip_str = args.next() orelse return error.MissingArg; + var ip_it = std.mem.splitScalar(u8, ip_str, '.'); + var ip: [4]u8 = undefined; + for (0..4) |i| { + const octet = ip_it.next() orelse return error.InvalidIP; + ip[i] = try std.fmt.parseInt(u8, octet, 10); + } + cfg.public_ip = ip; + } else if (std.mem.eql(u8, arg, "--topic")) { + if (args.next()) |v| cfg.topic = v; + } else if (std.mem.eql(u8, arg, "--ask")) { + cfg.ask_message = args.next(); + } else if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) { + printUsage(); + return; + } + } + + var agent = try SwarmAgent.init(allocator, cfg); + defer agent.deinit(); + + try agent.start(); + + // If --ask was provided, discover an agent and send a message + if (cfg.ask_message) |message| { + // Try DHT discovery first + std.debug.print("Discovering agents on topic \"{s}\"...\n", .{cfg.topic}); + + // Give DHT some time to propagate, try a few times + var discovered: ?SwarmAgent.DiscoveredAgent = null; + for (0..10) |_| { + for (0..5) |_| { + try agent.p2p_instance.update(); + std.Thread.sleep(50 * std.time.ns_per_ms); + } + discovered = try agent.discoverAgents(); + if (discovered != null) break; + } + + if (discovered) |d| { + defer d.deinit(allocator); + std.debug.print("Found agent: {s} ({s}) at {s}:{d}\n", .{ d.name, d.model, d.ip, d.port }); + + // Connect to the discovered agent if not already connected + var addr_buf: [21]u8 = undefined; + const connect_addr = std.fmt.bufPrint(&addr_buf, "{s}:{d}", .{ d.ip, d.port }) catch unreachable; + + const peer_id = agent.connectToPeer(connect_addr) catch |err| { + std.debug.print("Failed to connect to discovered agent: {}\n", .{err}); + return; + }; + + const response = try agent.askAgent(peer_id, message); + defer allocator.free(response); + std.debug.print("\n=== Response from {s} ===\n{s}\n", .{ d.name, response }); + return; + } + + // Fallback: use directly connected peers + const peers = agent.getPeers(); + if (peers.len == 0) { + std.debug.print("No agents discovered and no peers connected.\n", .{}); + return; + } + + std.debug.print("No DHT discovery result, using connected peer.\n", .{}); + const response = try agent.askAgent(peers[0], message); + defer allocator.free(response); + std.debug.print("\n=== Response ===\n{s}\n", .{response}); + return; + } + + // Otherwise run as a daemon + try agent.run(); +} + +fn printUsage() void { + std.debug.print( + \\A2A Swarm Agent - DHT-based Agent Discovery + A2A Messaging + \\ + \\Agents join a P2P swarm via bootstrap and discover each other + \\through the DHT using topic keys. No central server needed. + \\ + \\Usage: swarm-agent [options] + \\ + \\Options: + \\ --name Agent name (default: agent) + \\ --port P2P listen port (default: 9000) + \\ --model LLM model name (default: llama3.2) + \\ --ollama-url Ollama endpoint (default: http://localhost:11434) + \\ --bootstrap Bootstrap node address + \\ --dht-id Bootstrap node's DHT node ID (64 hex chars) + \\ --public-ip Explicit public IP for NAT environments + \\ --topic Agent topic to advertise (default: a2a-swarm) + \\ --ask Send message to first discovered agent and exit + \\ --help, -h Show this help + \\ + \\Examples: + \\ + \\ # Start bootstrap node (first agent in the swarm): + \\ zig build run-swarm-agent -- --name bootstrap --port 9000 + \\ + \\ # Join swarm as a second agent: + \\ zig build run-swarm-agent -- --name alice --port 9001 \ + \\ --bootstrap 127.0.0.1:9000 --dht-id + \\ + \\ # Join and ask a question to discovered agent: + \\ zig build run-swarm-agent -- --name bob --port 9002 \ + \\ --bootstrap 127.0.0.1:9000 --dht-id \ + \\ --ask "What is 2+2?" + \\ + \\ # Use explicit public IP (for NAT/cloud servers): + \\ zig build run-swarm-agent -- --name server1 --port 9000 \ + \\ --public-ip 203.0.113.10 + \\ + , .{}); +}