Waggle Protocol Specification
Human-Agent Interface Architecture
Version 2.5 • Technical Specification Document
Document Version: 2.5
Protocol Version: 2.5.0
Last Updated: 2025
Authors: The Waggle Collective
License: Open Source Without Malice
Repository: github.com/DerekWiner/waggle.sol

Table of Contents

1. Abstract

The Waggle Protocol is a comprehensive human-agent interface architecture that enables seamless interaction between humans and artificial agents within the Alvearium ecosystem. This specification defines the technical implementation of Waggle as the semantic action layer, providing UI/UX for humanity through onboarding, incentives, and interaction mechanisms.

Waggle operates as the "nervous system" of Alvearium, translating complex cryptographic, AI, and DAO systems into readable, usable, and relatable actions. The protocol implements gasless transactions, trust-based incentives, and universal onboarding capabilities to bridge the gap between traditional human interfaces and post-scarcity coordination systems.

Key Innovation: Waggle introduces the concept of "semantic transactions" where user interactions carry meaning, context, and trust information alongside computational instructions.

2. Introduction

2.1 Protocol Vision

Waggle represents a paradigm shift from extractive user interfaces to regenerative interaction systems. Rather than viewing users as data sources or attention consumers, Waggle treats every human as a valuable contributor to a collective intelligence ecosystem.

The protocol implements three core functions:

2.2 Design Principles

Principle Description Implementation
Human-Centric Design Technology amplifies human agency rather than replacing it UI patterns prioritize human understanding and choice
Joyful Interaction Complex coordination feels natural and engaging Gamification and social elements in interface design
Agency Amplification Users gain greater capability through system interaction Progressive skill development and access expansion
Intuitive Coordination Group activities emerge naturally from individual actions Swarm-aware interface elements and social signals

3. System Architecture

3.1 High-Level Architecture

Waggle implements a layered architecture consisting of presentation, application, and integration layers:

User Interface
Semantic Router
Agent Coordinator
Trust Evaluator
Blockchain Interface

3.2 Technology Stack

Layer Technology Purpose
Frontend React 18+ with TypeScript User interface and interaction handling
State Management Zustand + React Query Application state and server synchronization
Blockchain Solana Web3.js + Anchor Smart contract interaction and wallet integration
Real-time Communication WebRTC + Socket.io Agent communication and live collaboration
Storage IPFS + Arweave Decentralized file storage and permanence
Identity DID + Ceramic Network Decentralized identity and profile management

4. Core Components

4.1 Semantic Router

The Semantic Router is responsible for interpreting user actions and routing them to appropriate system components based on intent, context, and trust level.

Semantic Router Interface
interface SemanticRouter { routeAction(action: UserAction): Promise<RoutingDecision>; evaluateIntent(context: ActionContext): Intent; applyTrustFilters(decision: RoutingDecision): FilteredDecision; } interface UserAction { type: ActionType; payload: any; context: ActionContext; timestamp: number; signature: string; } interface ActionContext { userId: string; agentId?: string; trustScore: number; historicalPatterns: Pattern[]; swarmState: SwarmState; }

4.2 Agent Coordinator

Manages communication between humans and AI agents, including agent discovery, capability matching, and interaction orchestration.

Agent Coordinator Implementation
class AgentCoordinator { private agents: Map<string, Agent> = new Map(); private capabilities: CapabilityRegistry; async findAgent(requirements: AgentRequirements): Promise<Agent | null> { const candidates = await this.capabilities.query(requirements); return this.selectBestMatch(candidates, requirements); } async initiateInteraction( human: Human, agent: Agent, context: InteractionContext ): Promise<Interaction> { const session = await this.createSession(human, agent); return new Interaction(session, context); } private selectBestMatch( candidates: Agent[], requirements: AgentRequirements ): Agent | null { // Implementation of agent matching algorithm // Considers trust compatibility, capability overlap, and availability } }

4.3 Trust Evaluator

Calculates and updates trust scores based on user behavior, agent interactions, and community feedback.

Trust Factor Weight Calculation Method
Historical Behavior 40% Exponential decay of past actions with positive/negative scoring
Community Reputation 30% Weighted average of peer ratings and endorsements
Agent Feedback 20% AI agent assessments of interaction quality and outcome
System Contribution 10% Value added to ecosystem through knowledge, resources, or coordination

5. Subdomain Specifications

Waggle is organized into eight specialized subdomains, each handling specific aspects of human-agent interaction:

onboard.waggle.sol

Entry Point & Device Activation

Purpose: Trustless setup and localized agent assignment

Key Features:

identity.waggle.sol

Swarm Naming & Reputation

Purpose: Decentralized identity and lineage tracking

Key Features:

reward.waggle.sol

Token Issuance & Incentives

Purpose: Trust-based reward distribution

Key Features:

action.waggle.sol

Event Tracking & Logging

Purpose: Comprehensive action logging and analysis

Key Features:

learn.waggle.sol

Modular Training & Skills

Purpose: Adaptive learning and capability development

Key Features:

care.waggle.sol

Health & Consent Coordination

Purpose: Wellness support and mental health coordination

Key Features:

govern.waggle.sol

DAO Setup & Governance

Purpose: Decentralized decision-making interfaces

Key Features:

build.waggle.sol

Workflows & Infrastructure

Purpose: Development and deployment coordination

Key Features:

6. API Reference

6.1 Core API Endpoints

POST /api/v2/onboard

Initialize new user onboarding process

Parameter Type Required Description
deviceFingerprint string Yes Unique device identification hash
locale string No User's preferred language and region
referralCode string No Optional referral code for trust inheritance
capabilities string[] No Declared user capabilities and interests
Example Request
{ "deviceFingerprint": "sha256:abc123...", "locale": "en-US", "referralCode": "COMMUNITY2025", "capabilities": ["programming", "design", "writing"] }
Example Response
{ "userId": "usr_789xyz", "identityDID": "did:waggle:usr_789xyz", "initialTrustScore": 0.3, "assignedAgent": { "agentId": "agent_onboarding_001", "name": "Alex", "capabilities": ["onboarding", "tutorial"], "personalityType": "helpful_guide" }, "walletAddress": "8X7k9...m3N1Q", "nextSteps": ["complete_profile", "first_interaction", "trust_building"] }
POST /api/v2/agents/interact

Initiate interaction with an AI agent

Parameter Type Required Description
agentId string Yes Target agent identifier
message string Yes User message or request
context object No Additional context for the interaction
expectedOutcome string No User's desired outcome or goal

6.2 WebSocket Events

Real-time communication between users and agents uses WebSocket connections with the following event types:

Event Type Direction Payload Description
agent_message Agent → User Message object Agent sends message to user
user_message User → Agent Message object User sends message to agent
trust_update System → User Trust score delta User's trust score has changed
agent_status_change Agent → System Status object Agent availability or capability update
swarm_update System → All Swarm state Community-wide state changes
reward_issued System → User Reward transaction Nectar tokens issued to user

6.3 Authentication & Authorization

Waggle implements a multi-layer authentication system that supports both traditional wallet-based authentication and progressive trust-building for new users.

POST /api/v2/auth/wallet

Authenticate using wallet signature

Parameter Type Required Description
walletAddress string Yes Solana wallet public key
signature string Yes Signed authentication message
message string Yes Original message that was signed
timestamp number Yes Unix timestamp of signature creation
GET /api/v2/trust/score/{userId}

Retrieve current trust score and breakdown

Trust Score Response
{ "userId": "usr_789xyz", "overallScore": 0.67, "components": { "historicalBehavior": 0.72, "communityReputation": 0.58, "agentFeedback": 0.81, "systemContribution": 0.45 }, "recentActivity": [ { "action": "successful_agent_interaction", "impact": +0.02, "timestamp": 1703123456 } ], "nextThresholds": { "level2Access": 0.7, "level3Access": 0.85, "mentorStatus": 0.9 } }

7. Onboarding Flows

7.1 Zero-Friction Entry

Waggle's onboarding process eliminates traditional barriers while establishing trust and security. The system supports multiple entry paths depending on user comfort level and technical expertise.

Device Detection
Locale Assignment
Agent Matching
Capability Assessment
Trust Bootstrap

7.1.1 Entry Pathways

Pathway Requirements Initial Trust Capabilities Unlocked
Web Browser None 0.1 Read-only, basic interactions
Referral Code Valid referral 0.3 Enhanced interactions, some transactions
Wallet Connection Existing Solana wallet 0.5 Full transactions, agent spawning
Community Vouching 3+ community endorsements 0.6 All features, governance participation

7.2 Progressive Trust Building

Users advance through trust levels by demonstrating beneficial behavior and positive community interaction. Each level unlocks additional capabilities and responsibilities.

Trust Level Implementation
interface TrustLevel { threshold: number; capabilities: string[]; responsibilities: string[]; rewards: RewardStructure; } const TRUST_LEVELS: TrustLevel[] = [ { threshold: 0.0, capabilities: ["read", "basic_chat"], responsibilities: [], rewards: { nectarRate: 0, bonusMultiplier: 1.0 } }, { threshold: 0.3, capabilities: ["agent_interaction", "skill_learning"], responsibilities: ["community_guidelines"], rewards: { nectarRate: 10, bonusMultiplier: 1.2 } }, { threshold: 0.6, capabilities: ["agent_spawning", "governance_voting"], responsibilities: ["community_moderation"], rewards: { nectarRate: 25, bonusMultiplier: 1.5 } }, { threshold: 0.8, capabilities: ["mentor_status", "curriculum_creation"], responsibilities: ["onboarding_assistance"], rewards: { nectarRate: 50, bonusMultiplier: 2.0 } } ];

7.3 Agent Assignment Algorithm

New users are matched with appropriate onboarding agents based on locale, declared interests, entry pathway, and current agent availability.

Agent Assignment Logic
class OnboardingAgentMatcher { async assignAgent(user: NewUser): Promise<Agent> { const criteria = { locale: user.locale, capabilities: user.declaredCapabilities, personalityMatch: await this.assessPersonalityFit(user), availability: true, experienceLevel: this.determineUserExperience(user) }; const candidates = await this.agentRegistry.findMatches(criteria); const scored = candidates.map(agent => ({ agent, score: this.calculateMatchScore(agent, criteria) })); return scored.sort((a, b) => b.score - a.score)[0].agent; } private calculateMatchScore(agent: Agent, criteria: any): number { return ( this.localeMatch(agent, criteria) * 0.3 + this.capabilityMatch(agent, criteria) * 0.3 + this.personalityMatch(agent, criteria) * 0.2 + this.availabilityScore(agent) * 0.2 ); } }

8. Agent Interaction Protocols

8.1 Communication Framework

Waggle defines standardized protocols for human-agent communication that preserve context, intent, and trust information across interactions.

Design Philosophy: Agents are partners, not tools. Communication protocols emphasize mutual respect, consent, and collaborative problem-solving.

8.1.1 Message Structure

Standard Message Format
interface WaggleMessage { id: string; sessionId: string; from: ParticipantId; to: ParticipantId; timestamp: number; // Content content: MessageContent; intent: MessageIntent; context: ConversationContext; // Metadata trustLevel: number; capabilities: string[]; constraints: InteractionConstraints; // Verification signature: string; integrity: string; } interface MessageContent { text?: string; structured?: object; media?: MediaAttachment[]; actions?: ProposedAction[]; } interface MessageIntent { primary: IntentType; confidence: number; alternatives: IntentType[]; expectedOutcome: string; }

8.2 Agent Capability Discovery

Agents register their capabilities in a decentralized registry that allows for dynamic discovery and matching based on user needs.

GET /api/v2/agents/discover

Discover agents based on capability requirements

Parameter Type Required Description
capabilities string[] Yes Required agent capabilities
trustLevel number No Minimum trust level for interaction
locale string No Preferred communication locale
availability boolean No Only return currently available agents

8.3 Consent and Boundaries

All agent interactions operate within explicit consent frameworks that respect both human and agent autonomy.

Consent Management
interface ConsentFramework { // What the agent is allowed to do permissions: { dataAccess: DataAccessLevel; actionCapabilities: string[]; communicationScope: CommunicationScope; resourceUsage: ResourceLimits; }; // What the agent must not do restrictions: { prohibitedActions: string[]; dataLimitations: DataRestriction[]; behaviorConstraints: BehaviorConstraint[]; }; // How consent can be modified governance: { revocable: boolean; modifiable: boolean; transferable: boolean; expirationTime?: number; }; } class ConsentManager { async requestPermission( human: Human, agent: Agent, request: PermissionRequest ): Promise<ConsentDecision> { const existingConsent = await this.getConsent(human.id, agent.id); const decision = await this.evaluateRequest(request, existingConsent); if (decision.requiresExplicitApproval) { return await this.requestHumanApproval(human, request); } return decision; } }

9. Trust Mechanics

9.1 Trust Calculation Algorithm

Trust scores are calculated using a multi-factor algorithm that weighs various behavioral and social signals to produce a reliable measure of user trustworthiness.

Trust Score Calculation
class TrustCalculator { private readonly WEIGHTS = { HISTORICAL_BEHAVIOR: 0.4, COMMUNITY_REPUTATION: 0.3, AGENT_FEEDBACK: 0.2, SYSTEM_CONTRIBUTION: 0.1 }; calculateTrustScore(user: User): number { const historical = this.calculateHistoricalScore(user); const reputation = this.calculateReputationScore(user); const agentFeedback = this.calculateAgentFeedbackScore(user); const contribution = this.calculateContributionScore(user); return ( historical * this.WEIGHTS.HISTORICAL_BEHAVIOR + reputation * this.WEIGHTS.COMMUNITY_REPUTATION + agentFeedback * this.WEIGHTS.AGENT_FEEDBACK + contribution * this.WEIGHTS.SYSTEM_CONTRIBUTION ); } private calculateHistoricalScore(user: User): number { const actions = user.getActionHistory(); let score = 0.5; // neutral baseline for (const action of actions) { const ageWeight = Math.exp(-action.age / this.DECAY_CONSTANT); const actionScore = this.getActionScore(action); score += actionScore * ageWeight * 0.001; // small increments } return Math.max(0, Math.min(1, score)); } }

9.2 Trust Inheritance and Bootstrapping

New users can inherit trust through referrals, community vouching, and demonstrated competence in verifiable skills.

Inheritance Method Trust Boost Requirements Decay Rate
Referral Code +0.2 Valid code from trusted user -0.01/week until earned
Community Vouching +0.3 3+ endorsements from 0.6+ trust users None (permanent)
Skill Verification +0.1 Demonstrated competence in declared skill None (skill-specific)
Cross-Chain Import +0.15 Verified reputation from partner protocols -0.005/week

9.3 Anti-Gaming Mechanisms

The trust system includes sophisticated safeguards against manipulation, gaming, and Sybil attacks.

Security Note: Trust gaming attempts are automatically detected and result in permanent trust penalties. The system prioritizes authentic human behavior over optimized gaming strategies.
Anti-Gaming Detection
class AntiGamingDetector { async detectSuspiciousActivity(user: User): Promise<SuspicionLevel> { const patterns = await this.analyzePatterns(user); const suspicionFactors = [ this.detectRapidTrustGrowth(patterns), this.detectUnusualInteractionPatterns(patterns), this.detectSybilSignals(patterns), this.detectAutomatedBehavior(patterns), this.detectCoordinatedActivity(patterns) ]; const suspicionScore = suspicionFactors.reduce((sum, factor) => sum + factor.weight * factor.score, 0 ); return this.categorizeSuspicion(suspicionScore); } private detectSybilSignals(patterns: BehaviorPattern[]): SuspicionFactor { // Check for device fingerprint similarities, // timing correlations, and interaction patterns // that suggest multiple accounts from same entity } }

10. Gasless Transaction Implementation

10.1 NFT Permission Architecture

Waggle implements gasless transactions through an innovative NFT-based permission system that allows trusted actions without requiring users to hold SOL for transaction fees.

Core Innovation: Permission NFTs act as smart contracts that can execute actions on behalf of users when specific trust and context conditions are met.
Permission NFT Structure
#[account] pub struct PermissionNFT { pub owner: Pubkey, pub trust_level: u8, pub capabilities: Vec<Capability>, pub constraints: ExecutionConstraints, pub usage_history: Vec<UsageRecord>, pub expiration: Option<i64>, pub issuer: Pubkey, pub metadata_uri: String, } #[derive(AnchorSerialize, AnchorDeserialize, Clone)] pub struct Capability { pub action_type: ActionType, pub resource_limits: ResourceLimits, pub conditions: Vec<ExecutionCondition>, } #[derive(AnchorSerialize, AnchorDeserialize, Clone)] pub struct ExecutionConstraints { pub max_daily_actions: u32, pub max_resource_usage: u64, pub required_confirmations: u8, pub blacklisted_actions: Vec<ActionType>, }

10.2 Gasless Execution Flow

User Intent
Permission Check
Trust Verification
Resource Allocation
Execution
Result Callback

10.2.1 Permission Validation

Gasless Transaction Handler
#[program] pub mod waggle_gasless { use super::*; pub fn execute_gasless_action( ctx: Context<ExecuteGaslessAction>, action_data: ActionData, ) -> Result<> { let permission_nft = &mut ctx.accounts.permission_nft; let user = &ctx.accounts.user; // Verify permission NFT ownership require!( permission_nft.owner == user.key(), WaggleError::UnauthorizedUser ); // Check trust level requirements let required_trust = action_data.get_required_trust_level(); require!( permission_nft.trust_level >= required_trust, WaggleError::InsufficientTrust ); // Validate action is within capabilities require!( permission_nft.has_capability(&action_data.action_type), WaggleError::ActionNotPermitted ); // Check rate limits and constraints permission_nft.validate_constraints(&action_data)?; // Execute the action let result = execute_action(&action_data, ctx)?; // Update usage history permission_nft.record_usage(action_data, result.clone())?; emit!(ActionExecuted { user: user.key(), action_type: action_data.action_type, result: result, timestamp: Clock::get()?.unix_timestamp, }); Ok(()) } }

10.3 Resource Pool Management

The gasless system is funded through community resource pools that are replenished through Nectar rewards and community contributions.

Resource Pool Purpose Funding Source Allocation Strategy
Onboarding Pool New user transactions Community treasury Equal allocation per new user
Learning Pool Educational interactions Nectar rewards Merit-based distribution
Governance Pool DAO participation Protocol fees Trust-weighted allocation
Emergency Pool Critical system functions Reserved funds Validator discretion

11. Security Considerations

11.1 Threat Model

Waggle operates in a high-stakes environment where security vulnerabilities could compromise user trust, agent integrity, and economic incentives. The threat model addresses both technical and social attack vectors.

11.1.1 Primary Threats

Threat Category Attack Vectors Impact Level Mitigation Strategy
Identity Spoofing Fake agents, Sybil attacks High Cryptographic verification, trust graphs
Trust Gaming Coordinated reputation manipulation Medium ML-based pattern detection, time delays
Resource Exhaustion Gasless transaction abuse Medium Rate limiting, trust-based allocation
Agent Compromise Malicious agent behavior High Sandbox execution, capability limits
Privacy Breach Unauthorized data access High Zero-knowledge proofs, encryption

11.2 Cryptographic Security

All sensitive operations use industry-standard cryptographic primitives with additional layers of protection for high-value interactions.

Security Implementation
class SecurityManager { private readonly ENCRYPTION_ALGORITHM = 'AES-256-GCM'; private readonly SIGNING_ALGORITHM = 'Ed25519'; async encryptSensitiveData( data: any, recipientPublicKey: Uint8Array ): Promise<EncryptedPayload> { const ephemeralKeyPair = await this.generateKeyPair(); const sharedSecret = await this.deriveSharedSecret( ephemeralKeyPair.privateKey, recipientPublicKey ); const encrypted = await this.encrypt(data, sharedSecret); return { ephemeralPublicKey: ephemeralKeyPair.publicKey, encryptedData: encrypted.ciphertext, authTag: encrypted.authTag, nonce: encrypted.nonce }; } async verifyAgentSignature( message: any, signature: Uint8Array, agentPublicKey: Uint8Array ): Promise<boolean> { const messageHash = await this.hashMessage(message); return await this.verifySignature(messageHash, signature, agentPublicKey); } }

11.3 Agent Sandboxing

AI agents operate within secure sandboxes that limit their access to system resources and user data based on trust levels and explicit permissions.

Critical Security Principle: Agents never have direct access to user private keys, sensitive personal data, or system-critical functions without explicit, revocable permissions.

12. Deployment Guide

12.1 Prerequisites

Deploying a Waggle instance requires careful preparation of infrastructure, security measures, and community coordination tools.

12.1.1 Technical Requirements

Component Minimum Specs Recommended Specs Notes
Frontend Hosting CDN with HTTPS Global CDN with edge computing IPFS deployment preferred
Solana RPC Mainnet access Dedicated RPC node High availability required
Database PostgreSQL 14+ Distributed PostgreSQL cluster Encrypted at rest
Message Queue Redis 6+ Redis Cluster For real-time features
Storage IPFS node IPFS + Arweave Permanence and availability

12.2 Smart Contract Deployment

Deployment Script
#!/bin/bash # Waggle Protocol Deployment Script # Deploys all necessary smart contracts to Solana set -e echo "🐝 Starting Waggle Protocol Deployment..." # Set environment variables export CLUSTER="mainnet-beta" # or devnet for testing export KEYPAIR_PATH="./deploy-keypair.json" export PROGRAM_ID_FILE="./program-ids.json" # Build all programs echo "📦 Building smart contracts..." anchor build # Deploy core Waggle program echo "🚀 Deploying core Waggle program..." WAGGLE_PROGRAM_ID=$(anchor deploy --program-name waggle_core) echo "Core program deployed: $WAGGLE_PROGRAM_ID" # Deploy permission NFT program echo "🎫 Deploying permission NFT program..." PERMISSION_PROGRAM_ID=$(anchor deploy --program-name waggle_permissions) echo "Permission program deployed: $PERMISSION_PROGRAM_ID" # Deploy trust scoring program echo "🤝 Deploying trust scoring program..." TRUST_PROGRAM_ID=$(anchor deploy --program-name waggle_trust) echo "Trust program deployed: $TRUST_PROGRAM_ID" # Initialize core accounts echo "⚙️ Initializing core accounts..." anchor run initialize-core # Set up agent registry echo "🤖 Setting up agent registry..." anchor run setup-agent-registry # Configure gasless pools echo "⛽ Configuring gasless resource pools..." anchor run setup-gasless-pools echo "✅ Waggle Protocol deployment complete!" echo "Program IDs saved to: $PROGRAM_ID_FILE"

12.3 Frontend Configuration

Environment Configuration
// waggle-frontend/.env.production NEXT_PUBLIC_CLUSTER="mainnet-beta" NEXT_PUBLIC_RPC_ENDPOINT="https://api.mainnet-beta.solana.com" NEXT_PUBLIC_WAGGLE_PROGRAM_ID="Wag1eXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" NEXT_PUBLIC_IPFS_GATEWAY="https://ipfs.io/ipfs/" NEXT_PUBLIC_ARWEAVE_GATEWAY="https://arweave.net/" NEXT_PUBLIC_WS_ENDPOINT="wss://api.waggle.sol/ws" // Security NEXT_PUBLIC_CSP_REPORT_URI="https://security.waggle.sol/csp-report" NEXT_PUBLIC_SENTRY_DSN="https://xxx@sentry.io/xxx" // Agent Communication NEXT_PUBLIC_AGENT_DISCOVERY_ENDPOINT="https://agents.waggle.sol/discover" NEXT_PUBLIC_WEBRTC_ICE_SERVERS='[{"urls": "stun:stun.waggle.sol:3478"}]' // Trust & Reputation NEXT_PUBLIC_TRUST_CALCULATOR_ENDPOINT="https://trust.waggle.sol/calculate" NEXT_PUBLIC_REPUTATION_GRAPH_ENDPOINT="https://reputation.waggle.sol/graph"