Skip to main content

StateSet iCommerce CLI

AI-powered command-line interface for autonomous commerce operations.

Philosophy

The StateSet CLI is built on the premise that commerce infrastructure should be designed for AI agents, not just humans. Think of it as “The SQLite of Commerce” — an embedded, zero-dependency commerce engine that:
  • Runs locally without cloud dependencies
  • Deterministic operations for agent reliability
  • Agentic Commerce Protocol (ACP) for standardized agent interactions
  • Safety-first architecture — read-only by default, explicit --apply for writes

Features

Core

  • Natural Language Interface - Ask Claude to perform commerce operations
  • Multi-Agent System - 17 specialized agents auto-route to the best handler
  • 90+ MCP Tools - Full commerce API exposed to Claude
  • Hybrid Vector Search - Semantic + BM25 search for products, customers, orders, and inventory (requires OPENAI_API_KEY)
  • Multi-turn Sessions - Resume conversations for complex workflows
  • Preview Mode - See what would happen before making changes
  • Direct Commands - Fast, non-AI mode for scripting
  • Interactive Chat - REPL for exploratory work

Sync & Streaming

  • VES Protocol v1.0 - Verifiable Event Sync with Ed25519 signatures
  • gRPC Streaming - Real-time bidirectional sync with sequencer
  • Event Outbox - SQLite-backed event sourcing with conflict resolution
  • Optimistic Concurrency - Base version tracking for safe multi-agent updates

Payments

  • Multi-Chain Stablecoins - USDC on Solana, Base, Ethereum, Arbitrum
  • SET Chain ssUSD - Yield-bearing stablecoin on StateSet L2
  • Bitcoin & Zcash - Native BTC and ZEC support
  • VES Key Derivation - Deterministic wallet addresses per agent

Infrastructure

  • Batch Processing - Sequential or parallel request processing
  • Interactive Tutorials - Guided onboarding for new users
  • SQLite/PostgreSQL - Flexible storage backends
  • Rich Output - ASCII tables, progress bars, formatted displays
  • Telemetry - Distributed tracing with --verbose and --stats

Installation

npm install -g @stateset/cli
Or run locally:
cd cli
npm install
npm link

Quick Start

Tip: ss is a shorthand alias for stateset.

Run the Tutorial

New to StateSet CLI? Start with the interactive tutorial:
stateset-tutorial quickstart

AI-Powered Mode

# List customers (read-only by default)
stateset "show me all customers"

# Check inventory
stateset "how much stock do we have of WIDGET-001?"

# Create a customer (requires --apply)
stateset --apply "create a customer named Alice with email [email protected]"

# Multi-turn workflow
stateset --apply "create an order for that customer with 2 widgets at $29.99"
stateset --apply --resume <session-id> "ship that order with tracking ABC123"

Interactive Chat

stateset-chat

# In chat:
> show me all orders
> /apply on
> create a product called Premium Widget with SKU WIDGET-001 at $29.99
> /status
> /exit

Direct Commands (No AI)

# Customer operations
stateset-direct customers list
stateset-direct customers get [email protected]

# Order operations
stateset-direct orders list
stateset-direct orders ship <order-id> TRACK123

# Inventory operations
stateset-direct inventory stock WIDGET-001
stateset-direct inventory adjust WIDGET-001 -5 "Sold 5 units"

# Vector search (hybrid semantic + BM25)
stateset-direct vector search products "wireless earbuds" 5

Batch Processing

# Process multiple requests sequentially (maintains session context)
echo "list customers" | stateset --stdin --json

# Process requests from file
stateset --batch requests.txt

# Parallel processing (faster, independent requests)
stateset --batch requests.txt --parallel 4 --json

# Parallel with write operations
stateset --apply --batch orders.txt --parallel 3

Commands

Primary Commands

CommandDescription
stateset "<request>"AI-powered interface (auto-routes to best agent)
stateset-chatMulti-turn interactive REPL
stateset-direct <resource> <action>Direct CLI (no AI required)

Specialized Agent Commands

CommandAgentDescription
stateset-checkoutcheckoutShopping cart & checkout flow (ACP)
stateset-ordersordersOrder lifecycle management
stateset-inventoryinventoryStock & reservation management
stateset-returnsreturnsRMA & refund processing
stateset-analyticsanalyticsSales metrics & forecasting
stateset-promotionspromotionsPromotions, discounts & coupons
stateset-subscriptionssubscriptionsSubscription plans & recurring billing
stateset-createstorefrontScaffold e-commerce storefronts
stateset-manufacturingmanufacturingBOM & work order management
stateset-paymentspaymentsPayment processing & refunds
stateset-shipmentsshipmentsShipment tracking & delivery
stateset-supplierssuppliersSupplier & purchase order management
stateset-invoicesinvoicesB2B invoice management
stateset-warrantieswarrantiesProduct warranty & claims
stateset-currencycurrencyMulti-currency & exchange rates
stateset-taxtaxTax calculation & compliance
stateset-paystablecoinNative crypto payments (USDC, ssUSD, BTC, ZEC)

Utility Commands

CommandDescription
stateset-configProfile and configuration management
stateset-doctorHealth check and diagnostics
stateset-eventsEvent management and webhooks
stateset-syncVerifiable Event Sync with sequencer
stateset-tutorialInteractive tutorials and onboarding
stateset-completionShell completion scripts (bash/zsh/fish)

Architecture

stateset-icommerce/
├── crates/
│   ├── stateset-core/       # Pure domain models (254 types, 18 modules)
│   ├── stateset-db/         # SQLite + PostgreSQL (53 tables)
│   └── stateset-embedded/   # High-level unified API (671+ methods)
├── bindings/
│   ├── node/                # @stateset/embedded (NAPI)
│   ├── python/              # stateset-embedded (PyO3)
│   └── wasm/                # WebAssembly for browsers
└── cli/
    ├── bin/                 # 26 CLI programs
    ├── src/
    │   ├── claude-harness.js    # Multi-agent SDK integration
    │   ├── mcp-server.js        # 90+ MCP tools for Claude
    │   ├── sync/                # VES Protocol & gRPC streaming
    │   │   ├── grpc-client.js   # Bidirectional gRPC client
    │   │   ├── engine.js        # Sync orchestration
    │   │   ├── outbox.js        # Event outbox (SQLite)
    │   │   ├── crypto.js        # Ed25519 signing & hashing
    │   │   └── proto/           # Protocol buffer definitions
    │   ├── chains/              # Multi-chain payment support
    │   │   ├── config.js        # Chain configurations
    │   │   ├── wallet.js        # VES key → wallet derivation
    │   │   ├── stablecoin.js    # Payment operations
    │   │   └── validation.js    # Address validation
    │   ├── permissions.js       # Fine-grained access control
    │   ├── telemetry.js         # Observability & tracing
    │   ├── errors.js            # Structured error handling
    │   ├── session.js           # Session persistence
    │   └── database.js          # Connection pooling
    └── .claude/
        ├── agents/          # 17 specialized agent definitions
        └── skills/          # Domain knowledge documents

Technology Stack

  • Rust Core - Pure domain logic with deterministic execution
  • @stateset/embedded - Native Node.js bindings via NAPI
  • Claude Agent SDK - AI agent framework with MCP tools
  • SQLite/PostgreSQL - Flexible database backends

Capabilities

Commerce Operations

DomainOperations
OrdersCreate, confirm, process, ship, deliver, cancel
CustomersProfiles, addresses, preferences, history
ProductsCatalog with variants and attributes
InventoryMulti-location stock, reservations, adjustments
CartsShopping cart with ACP checkout flow
ReturnsRMA processing with refund management
ShipmentsFulfillment tracking with carrier integration

Manufacturing Operations

DomainOperations
Bill of MaterialsCreate, manage, activate BOMs
Work OrdersProduction job management
ComponentsTrack component requirements

Financial Operations

DomainOperations
Multi-Currency35+ currencies (USD, EUR, GBP, JPY, BTC, ETH, USDC)
PaymentsCredit card, PayPal, cryptocurrency
RefundsMultiple payout methods
InvoicesB2B invoice management with payment terms
Purchase OrdersSupplier management and procurement
TaxMulti-jurisdiction tax calculation (US, EU, CA)

Promotions & Discounts

# Create promotions
stateset --apply "create a 20% off promotion called Summer Sale"
stateset --apply "create a buy 2 get 1 free promotion"
stateset --apply "create a free shipping promotion for orders over $50"

# Manage coupons
stateset --apply "create coupon SAVE20 with 100 use limit"
stateset "is coupon SAVE20 valid?"

# Apply to cart
stateset --apply "apply promotions to cart <cart-id>"

Subscriptions & Recurring Billing

# Create plans
stateset --apply "create a monthly plan called Coffee Club at $29.99 with 14 day trial"
stateset --apply "create an annual plan called Pro at $99.99"

# Manage subscriptions
stateset --apply "subscribe customer <id> to the Coffee Club plan"
stateset --apply "pause subscription <id>"
stateset --apply "skip next billing for subscription <id>"
stateset --apply "cancel subscription <id>"

# View history
stateset "show billing history for subscription <id>"

Manufacturing

# Bill of Materials
stateset-manufacturing "list all BOMs"
stateset-manufacturing --apply "create a BOM for product ASSEMBLY-001"
stateset-manufacturing --apply "add component PART-A qty 2 to BOM BOM-123"

# Work Orders
stateset-manufacturing "list pending work orders"
stateset-manufacturing --apply "create work order from BOM BOM-123 for 100 units"
stateset-manufacturing --apply "start work order WO-456"
stateset-manufacturing --apply "complete work order WO-456 with 98 units produced"

Tax Management

# Calculate tax
stateset "calculate tax for an order shipping to California"
stateset "what's the tax rate for New York?"
stateset "calculate tax for cart CART-123456"

# Tax jurisdictions
stateset "show me all tax jurisdictions"
stateset "what are the EU VAT rates?"
stateset "get tax info for Texas"

# Exemptions
stateset --apply "create tax exemption for customer abc123 - resale certificate"

Analytics & Forecasting

# Sales analytics
stateset "what's my total revenue this month?"
stateset "show me my best sellers"
stateset "who are my top customers?"

# Inventory health
stateset "what inventory needs attention?"
stateset "show me low stock items"

# Forecasting
stateset "predict inventory needs for next month"
stateset "forecast revenue for next quarter"

Safety Architecture

Read-Only by Default

All write operations are blocked by default. The CLI shows what would happen without making changes.
# Preview what would happen
stateset "create a customer named Bob"
# Output: "Would create customer: {email: ..., name: Bob}"

# Actually create the customer
stateset --apply "create a customer named Bob"
# Output: "Created customer: abc-123-def"

Permission Controls

FeatureDescription
Preview ModeDefault read-only operation
Confirmation ThresholdsHigh-value operations (>$1000) prompt for confirmation
Permission GatingFive levels: none, read, preview, write, admin
Spending LimitsMax order value, daily totals
Rate LimitingTool calls/minute, write ops/minute
Audit LoggingComplete operation history

Observability

# Verbose output with tracing
stateset --verbose "show me pending orders"

# Execution statistics
stateset --stats "process all returns"

# JSON output for integration
stateset --json "list customers"

Workflows

E-commerce Workflow

# Set up a product
stateset --apply "create a product called 'Premium Widget' with SKU WIDGET-001 at $29.99"

# Add inventory
stateset --apply "create inventory for WIDGET-001 with 100 units"

# Create a customer
stateset --apply "create customer [email protected] named Alice Smith"

# Create an order
stateset --apply "create an order for [email protected]: 2x WIDGET-001"

# Ship it
stateset --apply --resume <session> "ship that order with tracking FEDEX123"

Shopping Cart Checkout (ACP)

# Create a cart
stateset --apply "create a cart for [email protected]"

# Add items (multi-turn)
stateset --apply --resume <session> "add 2 Premium Widgets at $29.99"
stateset --apply --resume <session> "add 1 Deluxe Widget at $49.99"

# Set shipping address
stateset --apply --resume <session> "set shipping to Alice Smith, 123 Main St, Anytown, CA 90210"

# Apply discount
stateset --apply --resume <session> "apply discount code SAVE10"

# Check shipping options
stateset --resume <session> "what shipping options are available?"

# Complete checkout
stateset --apply --resume <session> "pay with credit card and complete checkout"

Cart Recovery

stateset "show me abandoned carts"
stateset "what items are in cart CART-123456?"

Inventory Management

# Check stock
stateset "how much WIDGET-001 do we have?"

# Restock
stateset --apply "add 50 units to WIDGET-001 - received shipment"

# Adjust for damage
stateset --apply "remove 3 units from WIDGET-001 - damaged in warehouse"

Processing Returns

# Create return
stateset --apply "create a return for order #12345 - item defective"

# Review and approve
stateset "show me pending returns"
stateset --apply "approve return <return-id>"

Multi-Currency Support

stateset "what's the exchange rate from USD to EUR?"
stateset "convert $100 USD to EUR"
stateset "list all exchange rates"
stateset --apply "set exchange rate USD to EUR at 0.92"
stateset --apply "enable currencies USD, EUR, GBP, JPY"

Stablecoin Payments

Send native cryptocurrency payments across multiple blockchains:
# List supported blockchains
stateset pay --chains

# Show agent wallet addresses
stateset pay --wallet                     # All chains
stateset pay --wallet --chain solana      # Specific chain

# Check stablecoin balance
stateset pay --balance --chain solana
stateset pay --balance --chain set_chain

# Send payment (preview mode - no actual transaction)
stateset pay --to 9WzDXwBb...WWWM --amount 50.00 --chain solana

# Execute real payment (requires --apply)
stateset pay --apply --to 9WzDXwBb...WWWM --amount 50.00 --chain solana

# Pay with ssUSD on SET Chain (yield-bearing stablecoin)
stateset pay --apply --to 0x1234...5678 --amount 100 --chain set_chain

# Include order metadata for audit trail
stateset pay --apply --to <addr> --amount 50 --chain solana --order ORD-123 --memo "Widget purchase"

# AI-powered payments
stateset --apply "pay 50 USDC to 9WzDXwBb...WWWM on Solana"
stateset "check my wallet balance on Base"
Supported Chains:
ChainTokenDescription
solanaUSDCFast, cheap, proven liquidity
solana_devnetUSDCTesting
set_chainssUSDStateSet L2, yield-bearing
baseUSDCCoinbase L2, low fees
ethereumUSDC/USDT/DAIMaximum security
arbitrumUSDCFast L2
zcashZECPrivacy-focused (t-addresses)
bitcoinBTCOriginal cryptocurrency

Supplier Management

# Manage suppliers
stateset-suppliers "list all suppliers"
stateset-suppliers --apply "create supplier Acme Corp"

# Purchase orders
stateset-suppliers --apply "create PO for 100 WIDGET-001 from Acme Corp"
stateset-suppliers --apply "approve purchase order PO-123"
stateset-suppliers --apply "send purchase order PO-123 to supplier"

B2B Invoicing

# Create and manage invoices
stateset-invoices "list all invoices"
stateset-invoices --apply "create invoice for order ORD-456"
stateset-invoices --apply "send invoice INV-123"
stateset-invoices "show overdue invoices"
stateset-invoices --apply "record $500 payment for invoice INV-123"

Storefront Creation

# Preview what would be created
stateset-create "create a store called Urban Thread"

# Create the project
stateset-create --apply "create a nextjs storefront for my coffee shop"

# Create in specific directory
stateset-create --apply --dir ~/projects "build an online bookstore"
Available templates: nextjs, nextjs-minimal, vite-react, astro

Event Sync (VES Protocol)

Synchronize events between agents and the StateSet Sequencer using the Verifiable Event Sync protocol:
# Check sync status
stateset sync status

# Push local events to sequencer
stateset sync push

# Pull new events from sequencer
stateset sync pull

# Start real-time streaming sync
stateset sync stream

# Subscribe to specific entities
stateset sync stream --entity-type order --entity-id ORD-123
gRPC Streaming for real-time sync:
import { GrpcSequencerClient } from '@stateset/cli/sync';

const client = new GrpcSequencerClient({
  url: 'sequencer.stateset.io:8081',
  tenantId: 'your-tenant-id',
  storeId: 'your-store-id',
  agentId: 'your-agent-id',
});

await client.connect();

// Push events
await client.pushEvents([{
  entityType: 'order',
  entityId: 'ORD-123',
  eventType: 'OrderCreated',
  payload: { status: 'pending', amount: 99.99 },
  baseVersion: 0,
}]);

// Subscribe to real-time updates
client.onEvent((event) => {
  console.log('Received:', event.eventType, event.entityId);
});

await client.startSyncStream();
VES Protocol Features:
  • Ed25519 cryptographic signatures for event integrity
  • Domain-separated hashing (VES_PAYLOAD_PLAIN_V1)
  • Optimistic concurrency with base version tracking
  • Automatic conflict detection and resolution
  • Global sequence numbers for ordering

Agent System

17 specialized agents handle different commerce domains:
AgentToolsPurpose
checkout14 ACP toolsShopping cart & payment flows
orders6 toolsOrder lifecycle & fulfillment
inventory6 toolsStock management & reservations
returns5 toolsRMA & refund processing
analytics10 toolsBusiness intelligence & forecasting
promotions10 toolsCampaigns, discounts, coupons
subscriptions15 toolsSubscription plans & recurring billing
manufacturing11 toolsBOM & work order management
payments5 toolsPayment processing & refunds
shipments5 toolsShipment tracking & delivery
suppliers8 toolsSupplier & purchase order management
invoices7 toolsB2B invoice management
warranties6 toolsProduct warranty & claims
currency8 toolsMulti-currency & exchange rates
tax9 toolsTax calculation & compliance
storefront12 toolsE-commerce site scaffolding
customer-serviceAll 87+ toolsFull-service fallback agent

Auto-Routing

The main stateset command automatically routes requests to the best agent based on:
  • Request content analysis
  • Confidence scoring
  • Domain keyword matching
  • Ambiguity detection

MCP Tools (90+ Total)

DomainCountExamples
Customers3list, get, create
Orders6list, get, create, update_status, ship, cancel
Products4list, get, get_variant, create
Inventory6get_stock, create_item, adjust, reserve, confirm, release
Returns5list, get, create, approve, reject
Carts/Checkout14create, add_item, set_address, set_payment, complete_checkout
Analytics10sales_summary, top_products, demand_forecast, revenue_forecast
Currency8get_rate, convert, set_rate, format
Tax9calculate_tax, calculate_cart_tax, get_rate, list_jurisdictions
Promotions10list, create, activate, create_coupon, validate_coupon, apply
Subscriptions15list_plans, create_plan, create_subscription, pause, resume, cancel
Manufacturing11list_boms, create_bom, create_work_order, complete_work_order
Payments5list, get, create, complete, create_refund
Shipments3list, create, deliver
Suppliers/POs6list_suppliers, create_supplier, create_purchase_order
Invoices5list, create, send, record_payment, get_overdue
Warranties4list, create, create_claim, approve_claim
Stablecoin4get_agent_wallet, get_wallet_balance, create_payment, list_chains

Configuration

Environment Variables

# Claude API key (required for AI mode)
export ANTHROPIC_API_KEY="sk-ant-..."

Database

# Default: ./store.db (SQLite)
stateset --db /path/to/mystore.db "list customers"

# In-memory database (testing)
stateset --db :memory: "list customers"

# PostgreSQL (enterprise)
# Configure via environment or config file

Flags Reference

FlagDescription
--db <path>Database path
--applyEnable write operations
--model <name>Claude model to use
--resume <id>Resume previous session
--jsonJSON output
--verboseReal-time telemetry
--statsExecution statistics
--parallel <n>Process batch requests in parallel
--batch <file>Read requests from file
--stdinRead requests from stdin
--helpShow help

Session Management

Sessions enable multi-turn conversations with context preservation:
# First request returns session ID
stateset --apply "create a cart for [email protected]"
# Output includes: Session ID: abc-123-def

# Resume to continue context
stateset --apply --resume abc-123-def "add 2 widgets at $29.99"
stateset --apply --resume abc-123-def "complete checkout"

Tutorials

Learn the CLI with interactive tutorials:
# List available tutorials
stateset-tutorial

# Run specific tutorials
stateset-tutorial quickstart    # Learn basics in 5 minutes
stateset-tutorial orders        # Order management
stateset-tutorial inventory     # Stock management
stateset-tutorial checkout      # Shopping cart flow
stateset-tutorial analytics     # Business intelligence

Shell Completions

Generate shell completion scripts:
# Bash
stateset-completion bash >> ~/.bashrc

# Zsh
stateset-completion zsh >> ~/.zshrc

# Fish
stateset-completion fish > ~/.config/fish/completions/stateset.fish

Command Reference

stateset - AI Agent

stateset [options] "<request>"

Options:
  --db <path>       Database path (default: ./store.db)
  --apply           Enable write operations
  --model <name>    Claude model
  --resume <id>     Resume previous session
  --json            JSON output
  --verbose         Show telemetry
  --stats           Show execution stats
  --parallel <n>    Parallel batch processing
  --batch <file>    Read requests from file
  --stdin           Read requests from stdin
  --help            Show help

stateset-chat - Interactive Mode

stateset-chat [options]

Options:
  --db <path>     Database path
  --apply         Start with write enabled
  --model <name>  Claude model

In-chat commands:
  /help           Show commands
  /status         Current settings
  /apply on|off   Toggle write mode
  /db <path>      Switch database
  /new            Start new session
  /exit           Exit

stateset-direct - Direct Commands

stateset-direct [options] <resource> <action> [args]

Options:
  --db <path>     Database path
  --json          JSON output
  --help          Show help

Resources:
  customers       Customer management
  orders          Order management
  products        Product catalog
  inventory       Stock management
  returns         Return processing

Error Handling

The CLI provides structured error handling with helpful suggestions:
# Permission errors
Error: Permission denied: 'create_customer' requires --apply flag

Suggestions:
 Add --apply flag to enable write operations
 Example: stateset --apply "your command here"
 Run without --apply first to preview what would happen

# Not found errors
Error: Customer '[email protected]' not found

Suggestions:
 Check that the customer ID is correct
 List available customers: stateset-direct customers list
 Use a partial ID (like git) - only a few characters needed if unique

Diagnostics

Run health checks:
stateset-doctor

# Check specific components
stateset-doctor --checks api,db,permissions

Development

cd cli
npm install
npm link

# Test
npm test                    # All tests
npm run test:unit          # Unit tests only
npm run test:integration   # Integration tests

# Run diagnostics
stateset-doctor

Programmatic Usage

The CLI modules can be used programmatically:
import {
  runAgentLoop,
  createErrorHandler,
  createSessionManager,
  createDatabaseManager,
  withContext
} from '@stateset/cli';

// Run an agent request
const result = await runAgentLoop({
  request: 'list all customers',
  dbPath: './store.db',
  allowApply: false
});

// Use with request context
await withContext({ agent: 'orders' }, async (ctx) => {
  ctx.logEvent('processing_order');
  // ... your code
});