Skip to content

Battery Swap Service: ABS Platform Implementation

Overview

The Battery Swap Service is the first concrete implementation of the ABS Platform, demonstrating how the Mealy FSM formalism handles real-world business logic for asset-based subscription services. The service now uses a registry-based architecture for centralized business logic management.

Architecture

Registry-Based Agent Architecture

The Battery Swap Service uses a centralized registry pattern where: - Business Logic: Centralized in models/battery-swap-service/agent-pool/battery-swap-registry.ts - Agent Files: Minimal wrappers that delegate to the registry - Consistency: All agents follow identical patterns - Maintainability: Changes only need to be made in one place

Agent Pool Structure

models/battery-swap-service/agent-pool/
├── battery-swap-registry.ts   # Centralized business logic (551 lines)
├── quota-agent.ts            # Quota management (62 lines)
├── payment-agent.ts          # Payment processing (67 lines)
├── inventory-agent.ts        # Inventory tracking (63 lines)
├── subscription-agent.ts     # Subscription lifecycle (68 lines)
├── service-agent.ts          # Service quality (67 lines)
└── termsheet-agent.ts        # Contract compliance (67 lines)

Business Model

Core Concept

  • Service: Battery swap access at designated stations
  • Asset: Electric vehicle batteries
  • Subscription: Monthly/annual plans with usage quotas
  • Payment: Subscription fees + usage-based charges

Agent Implementations

1. Quota Agent (quota-agent.ts)

Purpose: Tracks monthly swap quota usage Logic: quota-agent-v1 from registry Parameters: monthly_quota, reset_day, low_threshold_percentage Events: SWAP_COMPLETED, QUOTA_RESET, BONUS_SWAP Signals: QUOTA_EXHAUSTED, QUOTA_LOW

2. Payment Agent (payment-agent.ts)

Purpose: Manages payment processing and credit tracking Logic: payment-agent-v1 from registry Parameters: grace_period_days, late_fee_percentage, credit_limit Events: PAYMENT_RECEIVED, PAYMENT_FAILED, CREDIT_ADDED Signals: PAYMENT_OVERDUE, CREDIT_LOW, PAYMENT_SUCCESS

3. Inventory Agent (inventory-agent.ts)

Purpose: Manages battery inventory and stock levels Logic: inventory-agent-v1 from registry Parameters: initial_stock, low_threshold, restock_amount Events: BATTERY_ASSIGNED, BATTERY_RETURNED, INVENTORY_RESTOCKED Signals: INVENTORY_EMPTY, INVENTORY_LOW

4. Subscription Agent (subscription-agent.ts)

Purpose: Manages subscription lifecycle and renewal Logic: subscription-agent-v1 from registry Parameters: grace_period_days, renewal_reminder_days, auto_renewal_enabled Events: SUBSCRIPTION_CREATED, SUBSCRIPTION_RENEWED, PAYMENT_RECEIVED Signals: SUBSCRIPTION_EXPIRING, RENEWAL_DUE_SOON, GRACE_PERIOD_WARNING

5. Service Agent (service-agent.ts)

Purpose: Manages service quality and station operations Logic: service-agent-v1 from registry Parameters: max_wait_time_minutes, service_quality_threshold, station_maintenance_interval_hours Events: SERVICE_REQUESTED, SERVICE_COMPLETED, QUALITY_FEEDBACK Signals: HIGH_DEMAND, LONG_WAIT_TIME, QUALITY_DEGRADING

6. Termsheet Agent (termsheet-agent.ts)

Purpose: Manages contract compliance and terms enforcement Logic: termsheet-agent-v1 from registry Parameters: max_swaps_per_month, min_swap_interval_minutes, max_concurrent_vehicles Events: SWAP_ATTEMPTED, SWAP_COMPLETED, VEHICLE_REGISTERED Signals: MONTHLY_LIMIT_APPROACHING, COMPLIANCE_VIOLATION, OUTSIDE_SERVICE_HOURS

Registry Pattern Benefits

Code Reduction

  • Before: ~200-300 lines per agent file
  • After: ~60-70 lines per agent file
  • Total Reduction: ~75% less code across all agents

Maintainability

  • Single Source of Truth: All business logic in one registry file
  • Consistent Patterns: All agents use identical structure
  • Easy Updates: Changes only need to be made in the registry

Reusability

  • Shared Logic: Multiple agent instances can use the same logic
  • Parameter Customization: Each instance can have different parameters
  • Version Control: Easy to version and update agent logic

Mealy FSM Implementation

1. Payment Cycle FSM Template

{
  "name": "Battery Swap Payment FSM",
  "description": "Handles payment flow for battery swap subscriptions - Customer Pays",
  "states": [
    "PAYMENT_INITIAL",
    "WAIT_DEPOSIT", 
    "WAIT_RENEWAL",
    "WAIT_FINALPAY",
    "PAYMENT_COMPLETE"
  ],
  "inputs": [
    "CONTRACT_SIGNED",
    "DEPOSIT_PAID",
    "RENEWAL_PAID", 
    "FINAL_PAYMENT_PAID"
  ],
  "outputs": [
    "DEPOSIT_REQUIRED",
    "RENEWAL_REQUIRED",
    "SERVICE_ACTIVATED",
    "FINAL_PAYMENT_REQUIRED"
  ],
  "initial_state": "PAYMENT_INITIAL",
  "transitions": [
    {
      "id": "contract_signed",
      "from": "PAYMENT_INITIAL",
      "input": "CONTRACT_SIGNED", 
      "to": "WAIT_DEPOSIT",
      "outputs": ["DEPOSIT_REQUIRED"],
      "description": "Contract signed, waiting for deposit"
    },
    {
      "id": "deposit_paid",
      "from": "WAIT_DEPOSIT",
      "input": "DEPOSIT_PAID",
      "to": "WAIT_RENEWAL", 
      "outputs": ["SERVICE_ACTIVATED"],
      "description": "Deposit paid, service activated"
    },
    {
      "id": "renewal_paid",
      "from": "WAIT_RENEWAL",
      "input": "RENEWAL_PAID",
      "to": "WAIT_RENEWAL",
      "outputs": ["RENEWAL_REQUIRED"], 
      "description": "Renewal paid, continue service"
    },
    {
      "id": "final_payment",
      "from": "WAIT_RENEWAL",
      "input": "FINAL_PAYMENT_PAID",
      "to": "PAYMENT_COMPLETE",
      "outputs": ["FINAL_PAYMENT_REQUIRED"],
      "description": "Final payment completed"
    }
  ]
}

2. Service Cycle FSM Template

{
  "name": "Battery Swap Service FSM", 
  "description": "Handles service availability for battery swap - ABS Serves",
  "states": [
    "SERVICE_INITIAL",
    "SERVICE_SUBSCRIBED",
    "SERVICE_SUSPENDED", 
    "SERVICE_UNSUBSCRIBED",
    "SUBSCRIPTION_COMPLETE"
  ],
  "inputs": [
    "DEPOSIT_CONFIRMED",
    "RENEWAL_CONFIRMED",
    "SERVICE_REQUESTED",
    "SERVICE_SUSPENDED",
    "SUBSCRIPTION_CANCELLED",
    "SUBSCRIPTION_EXPIRED"
  ],
  "outputs": [
    "SERVICE_READY",
    "SERVICE_ACTIVATED", 
    "SERVICE_DENIED",
    "SERVICE_SUSPENDED"
  ],
  "initial_state": "SERVICE_INITIAL",
  "transitions": [
    {
      "id": "deposit_confirmed",
      "from": "SERVICE_INITIAL",
      "input": "DEPOSIT_CONFIRMED",
      "to": "SERVICE_SUBSCRIBED",
      "outputs": ["SERVICE_READY"],
      "description": "Deposit confirmed, service ready"
    },
    {
      "id": "renewal_confirmed", 
      "from": "SERVICE_SUBSCRIBED",
      "input": "RENEWAL_CONFIRMED",
      "to": "SERVICE_SUBSCRIBED",
      "outputs": ["SERVICE_ACTIVATED"],
      "description": "Renewal confirmed, service activated"
    },
    {
      "id": "service_requested",
      "from": "SERVICE_SUBSCRIBED", 
      "input": "SERVICE_REQUESTED",
      "to": "SERVICE_SUBSCRIBED",
      "outputs": ["SERVICE_ACTIVATED"],
      "description": "Service requested, service available"
    },
    {
      "id": "service_suspended",
      "from": "SERVICE_SUBSCRIBED",
      "input": "SERVICE_SUSPENDED", 
      "to": "SERVICE_SUSPENDED",
      "outputs": ["SERVICE_SUSPENDED"],
      "description": "Service suspended due to payment or quota issues"
    },
    {
      "id": "service_resumed",
      "from": "SERVICE_SUSPENDED",
      "input": "RENEWAL_CONFIRMED",
      "to": "SERVICE_SUBSCRIBED", 
      "outputs": ["SERVICE_ACTIVATED"],
      "description": "Service resumed after payment confirmation"
    }
  ]
}

FSM Interaction Pattern

Customer Journey Flow

  1. Contract Signing: Customer signs contract → Payment FSM moves to WAIT_DEPOSIT
  2. Deposit Payment: Customer pays deposit → Payment FSM moves to WAIT_RENEWAL, Service FSM moves to SERVICE_SUBSCRIBED
  3. Service Usage: Customer requests service → Z-Agents process detailed business logic
  4. Agent Processing: Z-Agent outputs can trigger service suspension or activation

FSM Coordination

  • Payment Cycle FSM: Manages payment flow (Customer Pays)
  • Service Cycle FSM: Manages service availability (ABS Serves)
  • Z-Agent Pool: Processes detailed business logic and generates signals

End-to-End Workflow

1. Service Plan Creation

mutation createServicePlan {
  createServicePlanTemplate(input: {
    customer_id: "template",
    name: "Battery Swap Basic Plan",
    description: "Monthly battery swap subscription with 10 swaps",
    service_usages: [{
      service_id: "battery-swap-service",
      current_asset: null,
      usage_limits: { "monthly_swaps": 10 }
    }],
    plan_terms: {
      plan_duration: "1 year",
      recurring_amount: 49.99,
      billing_cycle: "monthly",
      currency: "USD",
      commitment_period: "1 year",
      auto_renew: true,
      billing_cycle_count: 12,
      payment_methods: ["credit_card", "bank_transfer"],
      deposit_required: true,
      deposit_amount: 100.00,
      deposit_refundable: true,
      cancellation_notice_days: 30,
      proration_enabled: true
    },
    agent_pool: ["quota-agent-1", "payment-agent-1", "inventory-agent-1"]
  }) {
    id
    name
    service_cycle {
      current_state
    }
    payment_cycle {
      current_state
    }
  }
}

2. Customer Instance Creation

mutation createCustomerPlan {
  createServicePlanFromTemplate(
    template_id: "battery-swap-basic-template",
    customer_id: "customer-123",
    input: {
      custom_name: "John Doe's Battery Swap Plan",
      custom_plan_terms: {
        recurring_amount: 49.99,
        deposit_amount: 100.00
      }
    }
  ) {
    id
    name
    customer_id
    service_cycle {
      current_state
    }
    payment_cycle {
      current_state
    }
    agent_pool {
      id
      name
      logic
      params
      state
    }
  }
}

3. Z-Agent Pool Processing

mutation processStimulus {
  processZAgentPoolWithStimulus(
    service_plan_id: "plan-123",
    stimulus: "SWAP_COMPLETED",
    metadata: {
      swap_location: "station-001",
      battery_id: "battery-456",
      swap_duration_minutes: 3
    }
  ) {
    service_plan_id
    stimulus
    processed_at
    agent_responses {
      agent_id
      agent_name
      logic
      previous_state
      current_state
      signals_generated
    }
    generated_signals
  }
}

4. Service Plan Status Query

query getServicePlanStatus {
  servicePlan(id: "plan-123") {
    id
    name
    customer_id
    service_cycle {
      current_state
      state_history {
        from_state
        to_state
        timestamp
      }
    }
    payment_cycle {
      current_state
      state_history {
        from_state
        to_state
        timestamp
      }
    }
    agent_pool {
      id
      name
      logic
      params
      state
    }
    payment_records {
      timestamp
      action {
        payment_type
        payment_amount
      }
    }
    service_records {
      timestamp
      action {
        service_type
        service_amount
      }
    }
  }
}

Implementation Benefits

Registry-Based Architecture

  • Centralized Logic: All business logic in battery-swap-registry.ts
  • Consistent Patterns: All agents follow identical structure
  • Easy Maintenance: Changes only need to be made in one place
  • Code Reduction: ~75% less code across all agents

FSM-Driven State Management

  • Clear State Transitions: Payment and service cycles are well-defined
  • Event-Driven: State changes triggered by business events
  • Audit Trail: Complete history of state transitions
  • Predictable Behavior: Mathematical FSM formalism

Z-Agent Business Logic

  • Specialized Processing: Each agent handles specific business concerns
  • Signal Generation: Agents emit signals that can trigger FSM transitions
  • Stateful Processing: Agents maintain internal state for business logic
  • Parameterized Behavior: Agent behavior configurable via parameters

This implementation demonstrates how the ABS Platform handles real-world business logic through the combination of FSM state management and Z-Agent business processing, all managed through a clean registry-based architecture. ```