Files
zigp2p/examples/a2a/MULTI_AGENT_ORCHESTRATION.md
2026-02-06 21:03:59 -03:00

1115 lines
36 KiB
Markdown

# Multi-Agent Orchestration with Verifiable Inference
**Version:** 1.0
**Created:** February 2026
## Overview
This document describes how to build a decentralized multi-agent AI system using zig-p2p where:
1. An orchestrator agent coordinates 100+ remote agents
2. Agents collaborate to improve and answer queries
3. LLM inference is **verifiable** for payment purposes
4. Everything runs over encrypted P2P connections
---
## Table of Contents
1. [Architecture](#1-architecture)
2. [Agent Discovery & Routing](#2-agent-discovery--routing)
3. [Query Flow](#3-query-flow)
4. [Verification Methods](#4-verification-methods)
5. [Payment Protocol](#5-payment-protocol)
6. [Implementation Guide](#6-implementation-guide)
7. [Security Considerations](#7-security-considerations)
---
## 1. Architecture
### 1.1 Network Topology
```
┌─────────────────┐
│ User Query │
│ "Explain X" │
└────────┬────────┘
│
▼
┌──────────────────────────┐
│ Orchestrator Agent │
│ │
│ • Query routing │
│ • Response aggregation │
│ • Verification │
│ • Payment distribution │
└──────────────┬───────────┘
│
┌─────────────────────────────┼─────────────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐
│ Expert Agent 1 │ │ Expert Agent 2 │ │ Expert Agent N │
│ │ │ │ │ │
│ Specialty: Legal │◄─────►│ Specialty: Medical│◄─────►│ Specialty: Tech │
│ Model: Llama-3 │ P2P │ Model: Med-LLM │ P2P │ Model: CodeLlama │
│ TEE: H100 CC │ │ TEE: AMD SEV │ │ TEE: Intel TDX │
└───────────────────┘ └───────────────────┘ └───────────────────┘
```
### 1.2 Agent Types
| Agent Type | Role | Verification |
|------------|------|--------------|
| **Orchestrator** | Routes queries, aggregates responses, manages payments | N/A (trusted) |
| **Expert Agent** | Runs LLM inference, provides specialized knowledge | TEE/zkML/Multi-party |
| **Validator Agent** | Verifies other agents' responses (spot-checking) | TEE required |
| **Relay Agent** | Helps with NAT traversal, no inference | Reputation only |
### 1.3 Capability Advertisement
Agents advertise their capabilities via DHT:
```zig
const AgentCapabilities = struct {
peer_id: PeerId,
specialties: []const []const u8, // ["legal", "tax", "corporate"]
models: []const ModelInfo, // Available models
verification_methods: []const VerificationMethod,
pricing: PricingInfo,
reputation_score: f32, // 0.0 - 1.0
stake_amount: u64, // Collateral staked
availability: Availability,
const ModelInfo = struct {
name: []const u8, // "llama-3-70b"
model_hash: [32]u8, // Hash of weights (for verification)
context_length: u32,
supports_deterministic: bool, // temperature=0 supported
};
const VerificationMethod = enum {
tee_nvidia_h100,
tee_amd_sev,
tee_intel_tdx,
tee_intel_sgx,
zkml_zkllm,
zkml_deepprove,
multi_party,
reputation_only,
};
const PricingInfo = struct {
price_per_1k_tokens: u64, // In smallest unit (e.g., satoshis)
currency: []const u8, // "BTC", "ETH", "USD"
min_query_size: u32,
max_query_size: u32,
};
};
```
---
## 2. Agent Discovery & Routing
### 2.1 DHT-Based Discovery
```zig
// Register agent capabilities in DHT
pub fn registerAgent(dht: *DHT, capabilities: AgentCapabilities) !void {
// Store under specialty keys for discovery
for (capabilities.specialties) |specialty| {
const key = hashSpecialty(specialty);
try dht.put(key, capabilities.serialize());
}
// Store under peer ID for direct lookup
try dht.put(capabilities.peer_id.toBytes(), capabilities.serialize());
}
// Find agents for a topic
pub fn findAgentsForTopic(dht: *DHT, topic: []const u8) ![]AgentCapabilities {
const key = hashSpecialty(topic);
const entries = try dht.get(key);
var agents = std.ArrayList(AgentCapabilities).init(allocator);
for (entries) |entry| {
const caps = try AgentCapabilities.deserialize(entry);
// Filter by verification requirements, reputation, etc.
if (caps.reputation_score >= MIN_REPUTATION) {
try agents.append(caps);
}
}
// Sort by reputation * availability / price
std.sort.sort(AgentCapabilities, agents.items, {}, compareAgentValue);
return agents.items;
}
```
### 2.2 Topic-Based Routing
```zig
const TopicRouter = struct {
subscriptions: std.StringHashMap(std.ArrayList(PeerId)),
pub fn subscribe(self: *TopicRouter, peer_id: PeerId, topic: []const u8) !void {
const entry = try self.subscriptions.getOrPut(topic);
if (!entry.found_existing) {
entry.value_ptr.* = std.ArrayList(PeerId).init(self.allocator);
}
try entry.value_ptr.append(peer_id);
}
pub fn routeToTopic(self: *TopicRouter, topic: []const u8, message: []const u8) !void {
if (self.subscriptions.get(topic)) |subscribers| {
for (subscribers.items) |peer_id| {
try self.p2p.send(peer_id, message);
}
}
}
};
```
---
## 3. Query Flow
### 3.1 Basic Query Flow
```
┌──────────┐ 1. Query ┌──────────────┐ 2. Route ┌─────────────┐
│ User │────────────►│ Orchestrator │─────────────►│ Agents │
└──────────┘ └──────────────┘ └─────────────┘
▲ │ │
│ │ │
│ 6. Final Answer │ 5. Verify & Pay │ 3. Inference
│ │ │
│ ▼ ▼
│ ┌──────────────┐ ┌─────────────┐
└───────────────────│ Aggregator │◄─────────────│ Responses │
└──────────────┘ 4. Collect └─────────────┘
```
### 3.2 Collaborative Query Flow
For complex queries requiring agent collaboration:
```
Time Action
────────────────────────────────────────────────────────────────────
T+0 User → Orchestrator: "What's the best legal structure for
an AI startup raising Series A?"
T+1s Orchestrator analyzes query:
- Topics: ["legal", "corporate", "startup", "fundraising"]
- Required expertise: Legal + Tax + VC
- Verification level: TEE (high-value query)
T+2s Orchestrator → DHT: Find agents for topics
Found: LegalAgent, TaxAgent, VCAgent, TechAgent
T+3s Orchestrator → All Agents:
{
query_id: "abc123",
type: "collaborative_query",
content: "What's the best legal structure...",
collaboration_mode: "discussion",
max_rounds: 3,
verification_required: "tee",
}
T+4s LegalAgent → All: "Delaware C-Corp is standard for VC"
(Includes TEE attestation)
T+5s TaxAgent → All: "C-Corp has double taxation, consider QSBS"
TechAgent → LegalAgent: "What about IP assignment?"
T+6s LegalAgent → All: "Good point, need PIIA agreements"
VCAgent → All: "Investors expect Delaware C-Corp, QSBS helps founders"
T+7s All Agents → Orchestrator: Final recommendations + attestations
T+8s Orchestrator:
- Verify all TEE attestations
- Synthesize responses
- Calculate payments based on contribution
T+9s Orchestrator → User: Synthesized answer
Orchestrator → Agents: Payment distribution
```
### 3.3 Message Protocol
```zig
const QueryMessage = struct {
header: MessageHeader,
payload: QueryPayload,
verification: ?VerificationData,
payment: ?PaymentData,
const MessageHeader = struct {
version: u8,
message_type: MessageType,
query_id: [16]u8,
timestamp: i64,
sender: PeerId,
signature: [64]u8,
};
const MessageType = enum(u8) {
query_request = 0x01,
query_response = 0x02,
collaboration_message = 0x03,
verification_request = 0x04,
verification_response = 0x05,
payment_commit = 0x06,
payment_release = 0x07,
fraud_proof = 0x08,
};
const QueryPayload = struct {
content: []const u8,
topics: []const []const u8,
collaboration_mode: CollaborationMode,
max_rounds: u8,
timeout_ms: u32,
verification_level: VerificationLevel,
max_price: u64,
};
const CollaborationMode = enum {
single_response, // One agent answers
parallel_independent, // Multiple agents, no interaction
discussion, // Agents can message each other
consensus, // Agents must agree on answer
};
const VerificationLevel = enum {
none, // Trust reputation only
tee_required, // Must have TEE attestation
zkml_required, // Must have zk proof
multi_party, // Require N confirmations
};
};
```
---
## 4. Verification Methods
### 4.1 TEE Attestation (Recommended)
Hardware-based proof that inference ran in a secure enclave.
```zig
const TEEAttestation = struct {
// Hardware signature from TEE
signature: [64]u8,
// What was executed
enclave_measurement: [32]u8, // Hash of code
model_hash: [32]u8, // Hash of model weights
// I/O binding
input_hash: [32]u8, // Hash of query
output_hash: [32]u8, // Hash of response
// Metadata
tee_type: TEEType,
timestamp: i64,
nonce: [16]u8, // Prevents replay
// Certificate chain for verification
certificate_chain: []const Certificate,
const TEEType = enum {
nvidia_h100_cc, // NVIDIA Confidential Compute
amd_sev_snp, // AMD Secure Encrypted Virtualization
intel_tdx, // Intel Trust Domain Extensions
intel_sgx, // Intel Software Guard Extensions
};
pub fn verify(self: *TEEAttestation, expected_model: [32]u8) !bool {
// 1. Verify certificate chain to hardware root
try self.verifyCertificateChain();
// 2. Verify enclave measurement (known good code)
if (!std.mem.eql(u8, &self.enclave_measurement, &KNOWN_ENCLAVE_HASH)) {
return error.InvalidEnclaveMeasurement;
}
// 3. Verify model hash
if (!std.mem.eql(u8, &self.model_hash, &expected_model)) {
return error.ModelMismatch;
}
// 4. Verify hardware signature
return try self.verifyHardwareSignature();
}
};
// P2P message with TEE attestation
const VerifiedResponse = struct {
query_id: [16]u8,
response: []const u8,
attestation: TEEAttestation,
pub fn verifyAndProcess(self: *VerifiedResponse, expected_model: [32]u8) ![]const u8 {
// Verify attestation
if (!try self.attestation.verify(expected_model)) {
return error.AttestationFailed;
}
// Verify output hash matches response
const response_hash = std.crypto.hash.sha2.Sha256.hash(self.response, .{});
if (!std.mem.eql(u8, &response_hash, &self.attestation.output_hash)) {
return error.ResponseTampered;
}
return self.response;
}
};
```
**Supported Hardware (2026):**
| Hardware | TEE Type | Overhead | Availability |
|----------|----------|----------|--------------|
| NVIDIA H100/H200 | Confidential Compute | 4-8% | Cloud (AWS, Azure, GCP) |
| AMD EPYC | SEV-SNP | 5-10% | Cloud + On-prem |
| Intel Xeon | TDX | 5-15% | Cloud + On-prem |
| Intel (older) | SGX | 10-20% | Limited memory |
### 4.2 zkML Verification
Cryptographic proof of correct inference.
```zig
const ZKMLProof = struct {
// The SNARK/STARK proof
proof: []const u8,
// Public inputs (visible to verifier)
public_inputs: struct {
model_commitment: [32]u8, // Pedersen commitment to weights
input_hash: [32]u8,
output_hash: [32]u8,
computation_hash: [32]u8, // Hash of circuit
},
// Proof system metadata
proof_system: ProofSystem,
prover_version: []const u8,
const ProofSystem = enum {
zkllm, // Specialized for LLMs
deepprove, // Lagrange Labs
zkpytorch, // Polyhedra Network
ezkl, // General ONNX support
};
pub fn verify(self: *ZKMLProof) !bool {
// Load verification key for the proof system
const vk = try loadVerificationKey(self.proof_system);
// Verify SNARK (fast: ~10ms)
return try verifySNARK(vk, self.proof, self.public_inputs);
}
};
```
**Current Performance (2026):**
| System | Model Size | Proof Time | Verify Time |
|--------|------------|------------|-------------|
| zkLLM | 13B params | ~15 min | ~10ms |
| DeepProve | GPT-2 | ~5 min | ~10ms |
| zkPyTorch | Llama-3-8B | ~2 min/token | ~10ms |
### 4.3 Multi-Party Verification
Query multiple agents, require consensus.
```zig
const MultiPartyVerification = struct {
query_id: [16]u8,
responses: std.AutoHashMap(PeerId, SignedResponse),
required_confirmations: u32,
similarity_threshold: f32,
const SignedResponse = struct {
response: []const u8,
signature: [64]u8,
timestamp: i64,
};
pub fn collectResponses(
self: *MultiPartyVerification,
p2p: *P2P,
agents: []const PeerId,
query: []const u8,
timeout_ms: u32,
) !void {
// Send query to all agents
for (agents) |agent| {
try p2p.send(agent, query);
}
// Collect responses with timeout
const deadline = std.time.milliTimestamp() + timeout_ms;
while (std.time.milliTimestamp() < deadline) {
if (try self.receiveResponse(p2p)) {
if (self.responses.count() >= self.required_confirmations) {
break;
}
}
}
}
pub fn findConsensus(self: *MultiPartyVerification) !ConsensusResult {
// Cluster responses by semantic similarity
var clusters = try self.clusterResponses();
// Find largest cluster
var largest: ?*ResponseCluster = null;
var largest_size: usize = 0;
for (clusters.items) |*cluster| {
if (cluster.members.items.len > largest_size) {
largest_size = cluster.members.items.len;
largest = cluster;
}
}
if (largest) |cluster| {
if (cluster.members.items.len >= self.required_confirmations) {
return .{
.verified = true,
.consensus_response = cluster.representative,
.agreeing_agents = cluster.members.items,
.confidence = @as(f32, @floatFromInt(cluster.members.items.len)) /
@as(f32, @floatFromInt(self.responses.count())),
};
}
}
return .{ .verified = false, .reason = .no_consensus };
}
fn clusterResponses(self: *MultiPartyVerification) !std.ArrayList(ResponseCluster) {
// Use embedding similarity or LLM-as-judge
// Group semantically equivalent responses
var clusters = std.ArrayList(ResponseCluster).init(self.allocator);
var it = self.responses.iterator();
while (it.next()) |entry| {
var found_cluster = false;
for (clusters.items) |*cluster| {
const similarity = try computeSimilarity(
entry.value_ptr.response,
cluster.representative,
);
if (similarity >= self.similarity_threshold) {
try cluster.members.append(entry.key_ptr.*);
found_cluster = true;
break;
}
}
if (!found_cluster) {
var new_cluster = ResponseCluster.init(self.allocator);
new_cluster.representative = entry.value_ptr.response;
try new_cluster.members.append(entry.key_ptr.*);
try clusters.append(new_cluster);
}
}
return clusters;
}
};
```
### 4.4 Optimistic Verification with Fraud Proofs
Assume honest, allow challenges.
```zig
const OptimisticVerification = struct {
query_id: [16]u8,
response: []const u8,
response_hash: [32]u8,
provider: PeerId,
provider_signature: [64]u8,
stake_amount: u64,
dispute_window_blocks: u32,
submitted_at: i64,
// State
status: Status,
challenger: ?PeerId,
fraud_proof: ?FraudProof,
const Status = enum {
pending, // Within dispute window
finalized, // No challenge, payment released
challenged, // Under dispute
slashed, // Fraud proven, stake lost
};
const FraudProof = struct {
correct_response: []const u8,
proof_type: ProofType,
proof_data: []const u8, // TEE attestation or zkProof
challenger: PeerId,
const ProofType = enum {
tee_attestation,
zkml_proof,
consensus_mismatch,
};
};
pub fn submitFraudProof(
self: *OptimisticVerification,
challenger: PeerId,
correct_response: []const u8,
proof: FraudProof,
) !FraudProofResult {
// Verify the fraud proof
const proof_valid = switch (proof.proof_type) {
.tee_attestation => try verifyTEEAttestation(proof.proof_data),
.zkml_proof => try verifyZKProof(proof.proof_data),
.consensus_mismatch => try verifyConsensus(proof.proof_data),
};
if (!proof_valid) {
return .{ .success = false, .reason = .invalid_proof };
}
// Compare responses
if (std.mem.eql(u8, correct_response, self.response)) {
return .{ .success = false, .reason = .responses_match };
}
// Fraud proven!
self.status = .slashed;
self.challenger = challenger;
self.fraud_proof = proof;
return .{
.success = true,
.slashed_amount = self.stake_amount,
.challenger_reward = self.stake_amount / 2,
};
}
pub fn finalize(self: *OptimisticVerification, current_block: u64) !void {
if (self.status != .pending) return;
const submission_block = @divFloor(self.submitted_at, BLOCK_TIME_MS);
if (current_block >= submission_block + self.dispute_window_blocks) {
self.status = .finalized;
}
}
};
```
### 4.5 Hybrid Verification Strategy
Recommended approach combining multiple methods:
```zig
const HybridVerifier = struct {
config: VerificationConfig,
tee_verifier: TEEVerifier,
zkml_verifier: ZKMLVerifier,
multi_party: MultiPartyVerification,
reputation_db: *ReputationDatabase,
stake_registry: *StakeRegistry,
const VerificationConfig = struct {
// Tier thresholds
high_value_threshold: u64, // Above this: TEE required
medium_value_threshold: u64, // Above this: Multi-party
// Multi-party settings
min_confirmations: u32,
similarity_threshold: f32,
// Spot-check rate for zkML auditing
zkml_audit_rate: f32, // e.g., 0.01 = 1%
// Stake requirements
min_stake_ratio: f32, // stake >= price * ratio
};
pub fn verify(
self: *HybridVerifier,
query: QueryMessage,
response: ResponseMessage,
) !VerificationResult {
const query_value = query.payload.max_price;
// Tier 1: High-value queries require TEE
if (query_value >= self.config.high_value_threshold) {
if (response.verification) |v| {
switch (v) {
.tee => |attestation| {
if (try attestation.verify(query.expected_model)) {
return .{ .verified = true, .method = .tee };
}
},
else => {},
}
}
return .{ .verified = false, .reason = .tee_required };
}
// Tier 2: Medium-value queries use multi-party
if (query_value >= self.config.medium_value_threshold) {
const consensus = try self.multi_party.findConsensus();
if (consensus.verified) {
return .{ .verified = true, .method = .multi_party };
}
return .{ .verified = false, .reason = .no_consensus };
}
// Tier 3: Low-value queries use reputation + stake
const provider = response.header.sender;
const reputation = self.reputation_db.get(provider);
const stake = self.stake_registry.get(provider);
if (reputation >= MIN_REPUTATION and
stake >= query_value * self.config.min_stake_ratio)
{
// Random spot-check with zkML
if (self.shouldSpotCheck()) {
return try self.requestZKMLProof(response);
}
return .{ .verified = true, .method = .reputation };
}
return .{ .verified = false, .reason = .insufficient_reputation };
}
fn shouldSpotCheck(self: *HybridVerifier) bool {
var rng = std.rand.DefaultPrng.init(@intCast(std.time.milliTimestamp()));
return rng.random().float(f32) < self.config.zkml_audit_rate;
}
};
```
---
## 5. Payment Protocol
### 5.1 Payment Flow
```
┌──────────────┐ ┌──────────────┐
│ Orchestrator │ │ Agent │
└──────┬───────┘ └──────┬───────┘
│ │
│ 1. Lock payment in escrow │
│─────────────────────────────────────────────│
│ │
│ 2. Query request │
│────────────────────────────────────────────►│
│ │
│ │ 3. Run inference
│ │ in TEE
│ │
│ 4. Response + Attestation │
│◄────────────────────────────────────────────│
│ │
│ 5. Verify attestation │
│ │
│ 6. Release payment │
│─────────────────────────────────────────────│
│ │
```
### 5.2 Payment Channel Implementation
```zig
const PaymentChannel = struct {
channel_id: [16]u8,
payer: PeerId,
payee: PeerId,
total_deposited: u64,
total_withdrawn: u64,
nonce: u64,
// Latest signed state
latest_state: SignedState,
const SignedState = struct {
channel_id: [16]u8,
balance_payer: u64,
balance_payee: u64,
nonce: u64,
payer_signature: [64]u8,
payee_signature: [64]u8,
};
pub fn pay(self: *PaymentChannel, amount: u64, reason: []const u8) !SignedState {
if (self.latest_state.balance_payer < amount) {
return error.InsufficientBalance;
}
const new_state = SignedState{
.channel_id = self.channel_id,
.balance_payer = self.latest_state.balance_payer - amount,
.balance_payee = self.latest_state.balance_payee + amount,
.nonce = self.nonce + 1,
.payer_signature = undefined,
.payee_signature = undefined,
};
// Sign with payer key
new_state.payer_signature = try self.signState(new_state);
return new_state;
}
};
const PaymentManager = struct {
channels: std.AutoHashMap(PeerId, PaymentChannel),
pending_payments: std.AutoHashMap([16]u8, PendingPayment),
const PendingPayment = struct {
query_id: [16]u8,
agent: PeerId,
amount: u64,
locked_at: i64,
verification_required: VerificationLevel,
status: PaymentStatus,
};
const PaymentStatus = enum {
locked,
released,
refunded,
disputed,
};
pub fn lockPayment(
self: *PaymentManager,
query_id: [16]u8,
agent: PeerId,
amount: u64,
verification: VerificationLevel,
) !void {
try self.pending_payments.put(query_id, .{
.query_id = query_id,
.agent = agent,
.amount = amount,
.locked_at = std.time.timestamp(),
.verification_required = verification,
.status = .locked,
});
}
pub fn releasePayment(
self: *PaymentManager,
query_id: [16]u8,
verification_result: VerificationResult,
) !void {
if (self.pending_payments.getPtr(query_id)) |payment| {
if (!verification_result.verified) {
payment.status = .refunded;
return;
}
// Release to agent
if (self.channels.getPtr(payment.agent)) |channel| {
_ = try channel.pay(payment.amount, "query response");
payment.status = .released;
}
}
}
};
```
### 5.3 Stake Registry
```zig
const StakeRegistry = struct {
stakes: std.AutoHashMap(PeerId, StakeInfo),
const StakeInfo = struct {
amount: u64,
locked_until: i64,
slashing_history: std.ArrayList(SlashEvent),
};
const SlashEvent = struct {
amount: u64,
reason: []const u8,
query_id: [16]u8,
timestamp: i64,
};
pub fn slash(
self: *StakeRegistry,
agent: PeerId,
amount: u64,
reason: []const u8,
query_id: [16]u8,
) !void {
if (self.stakes.getPtr(agent)) |stake| {
const slash_amount = @min(amount, stake.amount);
stake.amount -= slash_amount;
try stake.slashing_history.append(.{
.amount = slash_amount,
.reason = reason,
.query_id = query_id,
.timestamp = std.time.timestamp(),
});
}
}
};
```
---
## 6. Implementation Guide
### 6.1 Orchestrator Agent
```zig
const OrchestratorAgent = struct {
allocator: std.mem.Allocator,
p2p: *P2P,
dht: *DHT,
verifier: HybridVerifier,
payment_manager: PaymentManager,
reputation_db: ReputationDatabase,
// Active queries
active_queries: std.AutoHashMap([16]u8, ActiveQuery),
const ActiveQuery = struct {
query: QueryMessage,
responses: std.ArrayList(ResponseMessage),
started_at: i64,
status: QueryStatus,
};
pub fn submitQuery(
self: *OrchestratorAgent,
content: []const u8,
topics: []const []const u8,
config: QueryConfig,
) ![16]u8 {
const query_id = generateQueryId();
// 1. Find suitable agents
var agents = std.ArrayList(AgentCapabilities).init(self.allocator);
for (topics) |topic| {
const topic_agents = try self.dht.findAgentsForTopic(topic);
for (topic_agents) |agent| {
if (self.meetsRequirements(agent, config)) {
try agents.append(agent);
}
}
}
// 2. Select agents based on strategy
const selected = try self.selectAgents(agents.items, config);
// 3. Lock payments
for (selected) |agent| {
try self.payment_manager.lockPayment(
query_id,
agent.peer_id,
agent.pricing.estimatePrice(content.len),
config.verification_level,
);
}
// 4. Create and send query
const query = QueryMessage{
.header = .{
.query_id = query_id,
.message_type = .query_request,
.timestamp = std.time.timestamp(),
.sender = self.p2p.getLocalId(),
},
.payload = .{
.content = content,
.topics = topics,
.collaboration_mode = config.collaboration_mode,
.verification_level = config.verification_level,
},
};
for (selected) |agent| {
try self.p2p.send(agent.peer_id, query.serialize());
}
// 5. Track query
try self.active_queries.put(query_id, .{
.query = query,
.responses = std.ArrayList(ResponseMessage).init(self.allocator),
.started_at = std.time.timestamp(),
.status = .waiting,
});
return query_id;
}
pub fn handleResponse(self: *OrchestratorAgent, response: ResponseMessage) !void {
const query_id = response.header.query_id;
if (self.active_queries.getPtr(query_id)) |query| {
// Verify response
const result = try self.verifier.verify(query.query, response);
if (result.verified) {
try query.responses.append(response);
// Release payment
try self.payment_manager.releasePayment(query_id, result);
// Update reputation
try self.reputation_db.recordSuccess(response.header.sender);
} else {
// Slash if staked
try self.handleVerificationFailure(response.header.sender, result);
}
// Check if query complete
if (self.isQueryComplete(query)) {
try self.finalizeQuery(query_id);
}
}
}
fn finalizeQuery(self: *OrchestratorAgent, query_id: [16]u8) ![]const u8 {
const query = self.active_queries.get(query_id) orelse return error.QueryNotFound;
// Synthesize responses
const synthesized = try self.synthesizeResponses(query.responses.items);
// Cleanup
_ = self.active_queries.remove(query_id);
return synthesized;
}
};
```
### 6.2 Expert Agent with TEE
```zig
const ExpertAgent = struct {
allocator: std.mem.Allocator,
p2p: *P2P,
capabilities: AgentCapabilities,
tee: TEEContext,
llm: LLMContext,
pub fn handleQuery(self: *ExpertAgent, query: QueryMessage) !void {
// Run inference in TEE
const inference_result = try self.tee.runSecure(struct {
fn run(ctx: *TEEContext, q: []const u8) !InferenceResult {
// This code runs inside the TEE
const response = try ctx.llm.generate(q);
// Generate attestation
const attestation = try ctx.generateAttestation(.{
.input_hash = std.crypto.hash.sha2.Sha256.hash(q, .{}),
.output_hash = std.crypto.hash.sha2.Sha256.hash(response, .{}),
.model_hash = ctx.llm.getModelHash(),
});
return .{
.response = response,
.attestation = attestation,
};
}
}.run, query.payload.content);
// Send response with attestation
const response = ResponseMessage{
.header = .{
.query_id = query.header.query_id,
.message_type = .query_response,
.timestamp = std.time.timestamp(),
.sender = self.p2p.getLocalId(),
},
.response = inference_result.response,
.verification = .{ .tee = inference_result.attestation },
};
try self.p2p.send(query.header.sender, response.serialize());
}
};
```
---
## 7. Security Considerations
### 7.1 Threat Model
| Threat | Impact | Mitigation |
|--------|--------|------------|
| Fake responses | Payment for no work | TEE attestation, zkML proofs |
| Model substitution | Lower quality, cost savings | Model hash in attestation |
| Replay attacks | Double payment claims | Nonces, timestamps |
| Sybil attacks | Fake consensus | Stake requirements, reputation |
| Collusion | Fake multi-party consensus | Economic penalties, random selection |
| Eclipse attacks | Isolation from honest peers | DHT redundancy, multiple bootstrap |
### 7.2 Economic Security
For optimistic verification to be secure:
```
Stake > Potential Profit from Cheating
If:
- Query price: $1
- Probability of being caught: 1% (spot-check rate)
- Slash amount: 100x query price
Then:
Expected profit from cheating = $1 - (0.01 * $100) = $0
Rational agent will be honest.
```
### 7.3 Privacy Considerations
| Data | Privacy Approach |
|------|------------------|
| Query content | Encrypt with recipient's key, TEE decrypts inside enclave |
| Response content | Encrypt before sending |
| Model weights | Never leave TEE, only commitment published |
| Agent identities | Pseudonymous (PeerId), optional real identity for reputation |
---
## References
- [zkLLM: Zero Knowledge Proofs for Large Language Models](https://arxiv.org/abs/2404.16109)
- [The Definitive Guide to ZKML (2025)](https://blog.icme.io/the-definitive-guide-to-zkml-2025/)
- [Confidential LLM Inference with TEEs](https://arxiv.org/abs/2509.18886)
- [Verifiable AI with TEEs - Oasis Network](https://oasis.net/blog/verifiable-ai-with-tees)
- [GPU TEE Deep Dive - Phala Network](https://phala.com/posts/Phala-GPU-TEE-Deep-Dive)
- [zkPyTorch - Polyhedra Network](https://blog.polyhedra.network/zkpytorch/)
---
*Document version: 1.0*
*Created: February 2026*