StateSet iCommerce Engine
The SQLite of Commerce - An embedded commerce engine for autonomous AI agents. No external services required β the engine, its database, and its event log run in your process.
AI agents that reason, decide, and executeβreplacing tickets, scripts, and manual operations across your entire commerce stack.
Looking to accept ChatGPT checkout? iCommerce 1.0 pairs with
stateset-acp-handleras the reference implementation of the Agentic Commerce Protocol. One container, 60 seconds:npx create-acp-commerce@latest my-store.
π Intelligent Commerce Protocol (ICP). This repo also hosts the open spec and reference implementations of ICP-1.0 β the operational lifecycle layer (quote, escrow, fulfillment, dispute, settlement) that sits between checkout protocols (ACP/AP2) and payment rails (x402/USDC). 40+ end-to-end tests across HTTP handler, MCP server (Claude Desktop / Cursor / Windsurf), on-chain custody contract, off-chain Settler daemon, and a cross-language conformance suite, verified by the dedicated ICP conformance workflow whenever ICP code changes. Start at ICP.md or jump to the partnership packet.
Install:
cargo add stateset-sdk --features full # Rust (recommended)
pip install stateset-embedded==1.24.0 # Python
npm install @stateset/embedded@1.24.0 # Node.js
npm install -g @stateset/cli@1.24.0 # CLI
gem install stateset_embedded -v 1.24.0 # RubyConnect an AI agent in one line (Claude Desktop, Cursor, any MCP client β
900+ commerce tools, writes gated behind --apply):
npx -y -p @stateset/cli stateset-mcp --db ./store.db # stdio, your database
npx -y -p @stateset/cli stateset-mcp-http # Streamable HTTP, protocol 2026-07-28, statelessZero to commerce in 5 lines:
use stateset_sdk::prelude::*;
let commerce = Commerce::new("store.db")?;
let customer = commerce.customers().create(CreateCustomer {
email: "alice@example.com".into(),
first_name: "Alice".into(),
last_name: "Smith".into(),
..Default::default()
})?;
let order = commerce.orders().create(CreateOrder {
customer_id: customer.id,
items: vec![CreateOrderItem {
sku: "WIDGET-001".into(),
name: "Widget".into(),
quantity: 2,
unit_price: rust_decimal_macros::dec!(29.99),
..Default::default()
}],
..Default::default()
})?;
println!("Order {} β ${}", order.order_number, order.total_amount);No database setup. No config files. No migrations to run. It just works.
10-Minute Quickstart β | API Reference | OpenAPI Spec | Security | Trust Foundation
- Why iCommerce β what's different about a commerce engine built for AI agents
- Engine-First Adoption β embed it, don't service-mesh it
- Embedded Agent Toolkit β OpenAI / LangGraph / server-side
- MCP Server β Claude Desktop / Cursor / Windsurf
- What's New in v1.24.0
- Architecture β Rust kernel, language bindings, operator runtime
- Quick Start β working snippets in every language
- Production Notes β running on Postgres, scaling, observability
- Domain Models, MCP Tools, AI Agents
- Key Features β full feature matrix grouped by domain
- Installation β package commands + per-language gotchas
- Language Bindings β Rust, Node, Python, Go, Java, Kotlin, Swift, .NET, Ruby, PHP, WASM
- Configuration β SQLite vs Postgres, env vars
- Examples & Development
- Project Structure β how the monorepo is laid out
- Core Concepts β ACP, safety architecture, event-driven design
Why iCommerce
Most commerce platforms expose APIs that AI agents can call. iCommerce is built for AI agents β with the protocol, runtime, and economic primitives that autonomous agents actually need to transact safely:
- π€ Agent-to-Agent (A2A) Commerce β agents negotiate, quote, escrow, and settle directly. Reputation and verification built in. Splits, subscriptions, conditional payments, webhook events.
- π³ x402 Payment Protocol β cryptographically verifiable AI-agent payment intents (Ed25519, replay-protected nonces, optional PQC). On-chain settlement on Solana, SET Chain, Base, Ethereum, Arbitrum.
- π§ Autonomous Engine β scheduled jobs, state-machine workflows, policy-as-code rules, webhook event handlers, and human-in-the-loop approvals. One stack to run a business unattended.
- π Policy DSL β declarative, deny-overrides rules with explainable denials. Block agents from writes when limits are exceeded; record the reason for every decision.
-
π οΈ 898 MCP Tools across 87 domain modules β
the largest known domain-specific MCP surface, generated from the domain
registry (
cli/docs/TOOLS.mdis the source of truth). Discoverable, payable per call via Machine Payments Protocol, replayable, audit-logged. - π Verifiable Encrypted Signatures (VES v1.0) β Merkle-anchored event log with Ed25519 + ML-DSA-65 hybrid signatures and X25519 + ML-KEM-768 hybrid encryption. Every state change is signed and reconstructable.
- βοΈ Embedded engine, not a service β single-process SQLite by default, PostgreSQL when you scale up. No separate database to provision. No network hops between agent and runtime.
Most of the differentiators above are not "coming soon" β they're shipping in
v1.0.x. See AGENTIC_COMMERCE.md for the full A2A
case study and TRUST_FOUNDATION.md for the security
and verification architecture (including the explicit gap inventory: PQC hard
finality and SOC 2 are honest "in progress" items, not aspirational claims).
Engine-First Adoption
If the bet is the engine, the primary product surface is the embedded runtime:
- embed
@stateset/embeddedorstateset-sdkinside the agent host process - expose tools through
@stateset/embedded/openai,@stateset/embedded/generic,@stateset/embedded/langchain, or@stateset/embedded/vercel-ai - integrate with agent frameworks through native adapters or OpenAI-compatible tool schemas
- treat the MCP server as a distribution path for MCP-native clients, not as the center of the product
Today the embedded toolkit supports:
- OpenAI Responses / Chat Completions style tool loops via
@stateset/embedded/openai - Vercel AI SDK via
@stateset/embedded/vercel-ai - LangChain / LangGraph JS via
@stateset/embedded/langchain - framework-neutral runtimes via
@stateset/embedded/generic - Python agent runtimes via
create_embedded_agent_toolkit()instateset_embedded - Python framework helpers via
create_langchain_tools(),create_crewai_tools(), andcreate_autogen_tools() - Python OpenAI helper surface via
create_openai_tools()andexecute_openai_tool_call() - Python framework-neutral helper surface via
create_tool_descriptors(),create_callable_registry(), andexecute_tool() - Python framework modules via
stateset_embedded.langchain,stateset_embedded.crewai, andstateset_embedded.autogen - MCP-native clients like Claude Desktop / Cursor / Windsurf via the CLI server
For Python ecosystems such as CrewAI or AutoGen, the native Python toolkit now
covers core embedded commerce operations with OpenAI-compatible tool schemas,
framework-neutral descriptors, and framework adapter helpers. Install
stateset-embedded[agents] when you want the optional Python framework
dependencies in one step. Use the JS toolkit or MCP server when you need the
full registry-generated CLI surface, policy runtime, or priced-tool helpers.
The repo also includes dedicated Python example entry points for
stateset_embedded.generic, stateset_embedded.openai,
stateset_embedded.langchain, stateset_embedded.crewai, and
stateset_embedded.autogen under examples/python/, and the shared
check:engine-examples gate now exercises both the JS and Python engine
examples before release.
Embedded Agent Toolkit (OpenAI / LangGraph / server-side agents)
Use the embedded toolkit when your agent runtime lives inside your application process and wants JSON-schema tools instead of stdio MCP.
npm install @stateset/embedded@1.24.0 @stateset/cli@1.24.0import { Commerce } from '@stateset/embedded';
import { createOpenAITools, executeOpenAIToolCall } from '@stateset/embedded/openai';
const commerce = new Commerce('./store.db');
const tools = createOpenAITools(commerce, {
filter: ['list_customers'],
});
const execution = await executeOpenAIToolCall(commerce, {
call_id: 'demo_call_1',
function: {
name: 'list_customers',
arguments: '{}',
},
});
// execution.result.status === 'success'If your runtime should fan out to specialist agents, pass an autonomousEngine and enable writes for delegation:
const delegatedToolkit = createEmbeddedAgentToolkit({
commerce,
allowApply: true,
autonomousEngine,
});
await delegatedToolkit.executeTool('delegate_to_agent', {
agent_name: 'orders',
task_description: 'Review pending orders over $500',
context: { limit: 10 },
});delegate_to_agent follows the same safety model as other write tools, so it stays in preview mode until allowApply is enabled.
For OpenAI Responses API loops, executeOpenAIToolCall() returns a ready-to-send function_call_output payload:
const execution = await toolkit.executeOpenAIToolCall(toolCall);
await client.responses.create({
model: 'gpt-4.1',
previous_response_id: response.id,
input: [execution.outputMessage],
tools,
});For framework-native and framework-neutral adapters:
import { createVercelAITools } from '@stateset/embedded/vercel-ai';
import { createLangChainTools } from '@stateset/embedded/langchain';
import { createToolDescriptors } from '@stateset/embedded/generic';
const vercelTools = createVercelAITools(commerce, { tool });
const langChainTools = createLangChainTools(commerce, { DynamicStructuredTool });
const genericTools = createToolDescriptors(commerce);createToolDescriptors() is the lowest-common-denominator adapter surface for runtimes that want { name, description, schema, execute } objects instead of a framework-specific wrapper.
For priced tools and remote MPP-enabled HTTP services, the same toolkit also exposes
payment-aware helpers such as getPayableToolCatalog(), prepareToolPayment(),
executePaidTool(), discoverRemotePaymentService(), and
createRemoteHttpToolDescriptors().
For contract-aware or replay-aware agents, the toolkit also exposes
getRuntimeContract(), simulatePlan(), executePlan(), replayMutation(),
and getReplayLog().
Use simulateMutation() or executePlan({ dryRun: true, ... }) before enabling writes, then turn on allowApply only for agents that should mutate commerce state.
MCP Server (Claude Desktop / Cursor / Windsurf)
StateSet exposes hundreds of commerce tools via the Model Context Protocol. Add it to your AI editor in one step. The exact current count and policy-domain breakdown are generated from code in the MCP Tool Inventory.
One-command onboarding (including OpenClaw):
npx -y -p @stateset/cli@latest stateset-setup --yes --quickstart --db ./store.dbThis writes an MCP config at .openclaw/mcp.json and wires stateset-mcp-events automatically.
It also installs starter guardrail policies + an agent prompt pack under ./.stateset/.
--quickstart enables: --demo --agent openclaw --starter-pack ops --agent-only --verify.
It also generates ./.stateset/agent-starters/start-mcp.sh and check-mcp.sh for launch + health checks.
For a fully explicit run, use:
npx -y -p @stateset/cli@latest stateset-setup --yes --demo --agent openclaw --starter-pack ops --print-handoff --verify --db ./store.dbUse --agent claude, --agent cursor, or --agent windsurf for those clients, or pass
--mcp-config <path> for any MCP-compatible agent runtime.
Use --starter-pack support or --starter-pack checkout for different operating modes.
Use --agent-only when you only need MCP onboarding and don't want to require a local Anthropic key.
Use --verify-strict in CI to fail setup if any readiness warnings are present.
Claude Desktop β add to ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"stateset-commerce": {
"command": "npx",
"args": ["-y", "-p", "@stateset/cli@latest", "stateset-mcp-events"],
"env": { "DB_PATH": "./store.db" }
}
}
}Cursor β add to .cursor/mcp.json in your project:
{
"mcpServers": {
"stateset-commerce": {
"command": "npx",
"args": ["-y", "-p", "@stateset/cli@latest", "stateset-mcp-events"],
"env": { "DB_PATH": "./store.db" }
}
}
}This gives your AI assistant access to the full commerce stack: orders, inventory, customers, products, payments, returns, subscriptions, analytics, promotions, manufacturing, warehouse/fulfillment, general ledger, AP/AR, fixed assets, revenue recognition, A2A commerce, stablecoin payments, and more.
Development toolchain (repo root):
nvm use # uses .nvmrc / .node-version (20.20.0)
rustup show active-toolchain # dev toolchain pinned by rust-toolchain.toml (1.90.0)
npm run check # developer gate for the core workspace surfaces
npm run check:release # release preflight before cutting a tagThe authoritative remote release gate is the GitHub Actions CI Success job in
.github/workflows/ci.yml. A release tag should only be cut from a commit that
passes both npm run check:release locally and CI Success remotely.
CI also verifies the workspace MSRV on Rust 1.85 and runs the wider binding and admin surfaces under the same pinned Node 20.20.0 runtime.
What's New in v1.24.0
v1.24.0 moves the HTTP MCP server to protocol revision 2026-07-28 and
makes it stateless: stateset-mcp-http now serves through the MCP
SDK's per-request server factory, so it issues no session ids, retains
nothing between requests, and scales across replicas behind a load
balancer. 2025-era clients are still served, from the same tool factory,
unless you pass --strict-protocol.
v1.23.3β.6 completed the registry repair: per-platform npm packages
(~20 MB installs instead of a 184 MB bundle), Python wheels for 3.13 /
linux-arm64 / Intel macOS, and publish gates that catch fresh-consumer
breakage before it ships. v1.23.1/.2 were critical fixes for Rust
consumers: every previously
published crate version failed to compile on a fresh cargo add
(pre-release pqc dependencies drifted under cargo's semver matching;
docs.rs had never built). Now on stable ml-dsa/ml-kem with
wire-format vectors verified unchanged.
The v1.17.0 β v1.24.0 series makes the platform whole: full backend parity, complete language-binding coverage, a real disaster-recovery story, a broad operator console, and a complete core-commerce tool surface β closing the gaps the back-office build-out left behind.
- Trunk health and financial-correctness fixes (v1.24.0). First fully-green core CI; two real GL/AR PostgreSQL bugs fixed (nondeterministic auto-posting config, numeric decode); durable idempotency expiry boundary aligned across backends; 26 domains gained CLI command modules; every published crate now has a verified README.
- Core commerce is no longer the thinnest-tooled surface. Customers, products, and returns exposed only 5β6 binding methods and 3β5 MCP tools over 13β17-method engine accessors β the everyday operations were the least reachable in the catalog. 26 napi binding methods and 25 MCP tools close that gap: an agent can now update a customer and manage its address book, search products and manage variants and lifecycle, and run the full RMA return workflow (mark received, complete, cancel, add tracking, list by order/customer/pending). See the generated tool inventory for the current tool and domain counts.
-
Full PostgreSQL domain parity. All 34 repository capabilities now
return real stores on Postgres β 12 new implementations plus 13
previously built-but-unreachable stores wired into the
Databasefactory, verified by live-PG parity tests. TheNotPermittedshim layer is deleted; SQLite and PostgreSQL now expose the same surface. - Complete Node + Python binding coverage. Every embedded accessor is now bound in both bindings β the final accessors (activity logs, channels, companies, ERC-8004 identity/reputation/validation, and more) landed, and a binding-parity CI gate now fails the build if any future accessor is left unbound. Python caught up to Node across all 16 remaining domains.
-
898 MCP tools across 87 domains. The tool surface grew to match
the full binding surface (new EDI, prepayment, vendor-credit,
price-schedule, transfer-order, production-batch, supplier-SKU, and
inbound-shipment modules, among others), with the API-coverage gate
fully green. The generated catalog
(
cli/docs/TOOLS.md) remains the source of truth. -
Backup, restore, and portable export/import β the recovery story.
maintenance().backup_to()takes a consistentVACUUM INTOsnapshot (safe under concurrent writers) with a sidecar manifest recording schema version, migration count, engine version, size, and a verified SHA-256 checksum.restore_from()verifies the checksum, refuses backups newer than the running binary, and swaps atomically.export_all()/import_all()stream a versioned JSON envelope proven by an export β import β re-export round-trip test. All reachable from an agent via five MCP tools, so the engine can back up and restore the database it carries. - Admin Operations console. Purchasing (purchase orders, suppliers), warehouse (warehouses, locations, cycle counts), manufacturing (work orders, quality inspections, NCRs), fulfillment (waves, pick tasks), and traceability (lots with expiry highlighting, serials, receipts) pages β joining the earlier Finance module.
-
Two classes of latent bug fixed. Capability flags that reported
isSupported() == truewhile the underlying tables were missing (shipping_zones,search_config) are corrected with new migrations, and list-filter fields the stores silently ignored (purchase-order date/total ranges, quality inspection and NCR filters, plus PostgreSQL parameter-index and cursor-offset bugs) are now honored, each proven by a store-level test.
See CHANGELOG.md for the full per-release entries
(v1.17.0 β v1.24.0).
Earlier: the v1.8.0 β v1.16.0 back-office build-out
The v1.8.0 β v1.16.0 series turns the engine into a full back-office platform: a complete finance suite, full warehouse-management exposure, ~180 new REST endpoints, and a hardening pass across auth, idempotency, observability, and query discipline.
-
Complete finance suite. General ledger with journals
(post/void/reverse), trial balance, balance sheet, income statement,
period open/close/lock/reopen, idempotent FX revaluation
(
POST /gl/revalue), and one-shot month-end close orchestration (POST /gl/close-month: depreciation β revenue recognition β FX revaluation β period close, with dry-run and per-step reports). Accounts payable with 3-way match (PO β receipt β bill), payment runs, and aging. Accounts receivable with collections, dunning queues, credit memos, write-offs, and statements. A fixed-asset register with straight-line and declining-balance depreciation and disposal gain/loss. ASC 606-style revenue recognition (contracts, performance obligations, ratable / point-in-time / milestone schedules). - Full WMS exposure. Fulfillment waves with pick/pack/ship and cartons, receiving and put-away, warehouse locations with adjust/move, and cycle counts with transactional variance application.
- ~180 new REST endpoints, all documented in OpenAPI with tags and validated by the spec test suite β the finance and WMS backends above plus purchase orders + suppliers, work orders, quality (inspections, NCRs, holds), BOMs, lots, serials, carts/checkout, and backorders.
-
Admin Finance + EDI operations UI. Six finance pages (Ledger,
Bills, Close, Receivables, Assets, Revenue) and a read-only
/operations/edipage (850/855/856/810 summaries). -
Security hardening. Fail-closed API auth on non-loopback binds,
honest tenant isolation (
x-tenant-idon non-tenant deployments is rejected instead of silently sharing data), and durable DB-backed idempotency withIdempotency-Keyrequired by default on money mutations (428 when missing, 422 on fingerprint conflicts). -
Operability. Per-route Prometheus RED metrics (request/error
counts + latency histograms per method/route), cursor pagination
across list-heavy domains, server-side LIMIT policy on every list
query,
BEGIN IMMEDIATEon all SQLite write transactions, and 10 new webhook-subscribable domain events. - Test infrastructure. Property-based tests (proptest) over depreciation/revenue schedule math and 3-way-match tolerances, plus a seeded 200-operation randomized ledger simulation asserting the trial balance after every operation β which found and fixed real close-period and revenue-schedule bugs.
-
Binding parity. Node and Python expose the new domains
(fixed assets, revenue recognition, cycle counts, 3-way match,
GL revalue/close-month), with async API parity in Rust
(
AsyncCommerce) and a generated tool catalog (cli/docs/TOOLS.md, 898 tools across 87 domains) kept fresh by a regenerate-and-diff test.
See CHANGELOG.md for the full per-release entries
(v1.8.0 β v1.16.0).
v1.7.0 was a correctness and hardening release: safe-by-default
checkout (carts().complete() mints Confirmed orders with payment
Pending; out-of-band settlement via complete_settled_externally()),
exact-decimal money end to end, inventory reservation accounting fixes,
atomic checkout on Postgres, and per-client HTTP rate limiting.
v1.6.0 completed three-language SDK symmetry on the ICP trust
primitives: the Rust and Python SDKs gained verify_settlement_receipt
(mirroring the JS helper byte-for-byte), all three first-party SDKs ship
registerWebhook + verifyWebhook + fetchChannelEvents +
verifySettlementReceipt, and operator-facing integration guides landed
under icp-spec/guides/.
ICP-1.0 ships all seven core intent verbs β 100% of the addressable commerce verb surface:
-
inventory.queryβ discovery (read-only, highest call volume) -
purchase.createβ one-shot retail -
subscription.createβ recurring revenue (SaaS, streaming, B2B services) -
subscription.cancelβ signed, auditable subscription termination -
purchase.returnβ returns / refunds withmax_refundceiling -
quote.requestβ B2B wholesale RFQ (non-binding PriceProposal) -
payout.requestβ marketplace seller payouts (inverted signing)
The HTTP handler and the MCP server accept all seven; the HTTP handler
additionally accepts the channel.register extension verb (ICPIP-0005
push channels).
v1.1.0 introduced the Intelligent Commerce Protocol (ICP) reference
implementation set: normative spec, four cross-language conformance
IUTs (JavaScript / Rust / Go / Python β all byte-identical), HTTP and
MCP transports, on-chain custody contract (15/15 Foundry tests),
off-chain Settler daemon, Docker Compose deployment package, Foundation
charter, LOI template, and a partnership packet. See CHANGELOG.md
for the full release history.
Start at ICP.md for the discoverable entry point.
The 250k-LOC commerce engine continues to ship unchanged β ICP is additive infrastructure, not a refactor.
Documentation
- mdBook docs live in
docs/(seedocs/README.md). - API reference pointers per binding:
docs/src/api/. - End-to-end examples and workflows:
examples/. - Release history:
CHANGELOG.md. - Security policy:
SECURITY.md.
Support Matrix
| Tier | Whatβs Covered | CI Coverage |
|---|---|---|
| Tier 1 | Default-workspace Rust crates, Node binding, admin app, CLI | Verified by npm run check locally and required in CI Success
|
| Tier 2 | Python, Go, .NET, Java/Kotlin, Swift, and WASM bindings | Dedicated CI jobs are required in CI Success before tagging |
| Tier 3 | Ruby native gem and PHP extension distribution flows | Representative CI jobs plus release-workflow validation on publish commits |
Ruby and PHP are kept in-repo but intentionally excluded from default workspace
membership because they require host runtimes or headers that are often
unavailable in local dev. They are still exercised in dedicated CI lanes and
must not be released from a commit without a green CI Success aggregate.
Release Gate
- Local preflight:
npm run check:release - Remote tag gate: green
CI Successin.github/workflows/ci.yml - Local git hooks are convenience checks only; the release authority is the checked command above plus the protected CI aggregate
Production note: use config/stateset.production.properties as the baseline for secure defaults.
Architecture
This repository is best understood as a platform monorepo with a layered Rust kernel and two large outer product surfaces: language bindings and the Node-based operator runtime.
The current workspace manifests form this dependency direction:
stateset-primitives | stateset-crypto | stateset-pricing | stateset-observability
stateset-policy | stateset-authz | stateset-a2a | stateset-jobs
stateset-migrations | stateset-macros
->
stateset-core | stateset-sync
->
stateset-db
->
stateset-embedded
->
stateset-http | stateset-sdk | bindings/*
->
admin | cli
What Each Layer Does
| Layer | Primary crates/surfaces | Role |
|---|---|---|
| Foundation |
stateset-primitives, stateset-crypto, stateset-pricing, stateset-observability, stateset-policy, stateset-authz, stateset-a2a, stateset-jobs, stateset-migrations, stateset-macros
|
Narrow building blocks and cross-cutting capabilities |
| Domain kernel |
stateset-core, stateset-sync
|
Pure commerce logic, wire formats, sync/runtime contracts |
| Storage + product API |
stateset-db, stateset-embedded
|
Persistence and the main embeddable commerce surface |
| Edge adapters |
stateset-http, stateset-sdk, stateset-ffi, bindings/*
|
Transport, Rust facade, C-style interop, and language-specific packaging |
| Operator surfaces |
cli/, admin/
|
MCP, agents, automation, and admin UX |
Binding Topology
-
bindings/nodeis the shared JS-facing native layer and links directly tostateset-embedded,stateset-core,stateset-db, andstateset-crypto. - The admin app and CLI both consume
@stateset/embeddeddirectly rather than going throughstateset-sdk. - Python and the compiled language bindings also link directly to
stateset-embeddedandstateset-core; they are not all routed throughstateset-ffi. -
stateset-sdkis the Rust-facing facade for consumers that want one dependency with feature-gated re-exports. -
stateset-ffiis an optional C-ABI oriented interop surface, not the mandatory substrate for every binding in this repository.
Operational Surfaces
-
cli/is a large Node 20.20+ runtime with the MCP server, tool registry, sync/x402 logic, agent routing, messaging channels, and scaffolding flows. -
admin/is a Next.js surface that depends on the local Node binding package and loads@stateset/embeddedat runtime. - The root
npm run checkpipeline validates release hygiene, Rust fmt/tests/lints/feature-matrix checks, shell scripts, the Node binding, the admin app, and the CLI. -
npm run check:releaseis the authoritative local release preflight; it extendsnpm run checkwith doc-tool validation and generated inventory checks before a tag is cut.
Recommended Onboarding Order
stateset-corestateset-dbstateset-embedded-
stateset-sync,stateset-policy,stateset-authz,stateset-pricing stateset-http-
bindings/nodeand thenadmin/orcli/
For a manifest-grounded dependency walkthrough, see Dependency Direction.
Quick Start
Rust
use stateset_sdk::prelude::*;
use rust_decimal_macros::dec;
// Initialize with a local database file
let commerce = Commerce::new("./store.db")?;
// Create a customer
let customer = commerce.customers().create(CreateCustomer {
email: "alice@example.com".into(),
first_name: "Alice".into(),
last_name: "Smith".into(),
..Default::default()
})?;
// Create inventory
commerce.inventory().create_item(CreateInventoryItem {
sku: "SKU-001".into(),
name: "Widget".into(),
initial_quantity: Some(dec!(100)),
..Default::default()
})?;
// Create an order
let order = commerce.orders().create(CreateOrder {
customer_id: customer.id,
items: vec![CreateOrderItem {
sku: "SKU-001".into(),
name: "Widget".into(),
quantity: 2,
unit_price: dec!(29.99),
..Default::default()
}],
..Default::default()
})?;
// Ship the order
commerce.orders().ship(order.id, Some("FEDEX123456".into()))?;Node.js
const { Commerce } = require('@stateset/embedded');
async function main() {
const commerce = new Commerce('./store.db');
// Create a cart and checkout
const cart = await commerce.carts.create({
customerEmail: 'alice@example.com',
customerName: 'Alice Smith'
});
await commerce.carts.addItem(cart.id, {
sku: 'SKU-001',
name: 'Widget',
quantity: 2,
unitPrice: 29.99
});
const result = await commerce.carts.complete(cart.id);
console.log(`Order created: ${result.orderNumber}`);
// Convert currency
const conversion = await commerce.currency.convert({
from: 'USD',
to: 'EUR',
amount: 100
});
console.log(`$100 USD = β¬${conversion.convertedAmount} EUR`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});Python
from stateset_embedded import Commerce
commerce = Commerce('./store.db')
# Get analytics
summary = commerce.analytics.sales_summary(period='last30days')
print(f"Revenue: ${summary.total_revenue}")
print(f"Orders: {summary.order_count}")
# Forecast demand
forecasts = commerce.analytics.demand_forecast(days_ahead=30)
for f in forecasts:
if f.days_until_stockout and f.days_until_stockout < 14:
print(f"WARNING: {f.sku} will stock out in {f.days_until_stockout} days")Other bindings
Same Commerce API surface, idiomatic per language. Expand any block
to see the snippet β all ten bindings ship from the same Rust core
and pass the same cross-binding parity tests.
require 'stateset_embedded'
commerce = StateSet::Commerce.new('./store.db')
customer = commerce.customers.create(
email: 'alice@example.com', first_name: 'Alice', last_name: 'Smith'
)
order = commerce.orders.create(
customer_id: customer.id,
items: [{ sku: 'SKU-001', name: 'Widget', quantity: 2, unit_price: 29.99 }]
)
plan = commerce.subscriptions.create_plan(name: 'Pro', price: 29.99, interval: 'month')
commerce.subscriptions.subscribe(plan_id: plan.id, customer_id: customer.id)<?php
use StateSet\Commerce;
$commerce = new Commerce('./store.db');
$customer = $commerce->customers()->create(
email: 'alice@example.com', firstName: 'Alice', lastName: 'Smith'
);
$order = $commerce->orders()->create(
customerId: $customer->getId(),
items: [['sku' => 'SKU-001', 'name' => 'Widget', 'quantity' => 2, 'unit_price' => 29.99]]
);
$tax = $commerce->tax()->calculate(amount: 100.00, jurisdictionId: $jur->getId());import com.stateset.embedded.*;
try (Commerce commerce = new Commerce("./store.db")) {
Customer customer = commerce.customers().create("alice@example.com", "Alice", "Smith");
Order order = commerce.orders().create(customer.getId(), "USD");
commerce.payments().recordPayment(order.getId(), order.getTotalAmount(), "card", "txn_123");
SalesSummary s = commerce.analytics().salesSummary(30);
System.out.println("Revenue: $" + s.getTotalRevenue());
}import com.stateset.embedded.*
val commerce = StateSetCommerce("./store.db")
val customer = commerce.customers.create(
email = "alice@example.com", firstName = "Alice", lastName = "Smith"
)
val product = commerce.products.create(name = "Widget", sku = "SKU-001", price = 29.99)
commerce.orders.create(
customerId = customer.id,
items = listOf(OrderItem(product.id, "SKU-001", "Widget", 2, "29.99")),
currency = "USD",
)
commerce.close()import StateSet
let commerce = try StateSetCommerce(path: "./store.db")
defer { commerce.close() }
let customer = try commerce.customers.create(
email: "alice@example.com", firstName: "Alice", lastName: "Smith"
)
let product = try commerce.products.create(name: "Widget", sku: "SKU-001", price: 29.99)
let order = try commerce.orders.create(
customerId: customer.id,
items: [OrderItem(productId: product.id, sku: "SKU-001", name: "Widget", quantity: 2, unitPrice: "29.99")],
currency: "USD",
)
try commerce.orders.updateStatus(id: order.id, status: .shipped)using StateSet;
using var commerce = new StateSetCommerce("./store.db");
var customer = commerce.Customers.Create(
email: "alice@example.com", firstName: "Alice", lastName: "Smith"
);
var product = commerce.Products.Create(name: "Widget", sku: "SKU-001", price: 29.99m);
commerce.Orders.Create(
customerId: customer.Id,
items: new[] {
new OrderItem { ProductId = product.Id, Sku = "SKU-001", Name = "Widget", Quantity = 2, UnitPrice = "29.99" }
},
currency: "USD",
);package main
import (
"fmt"
"github.com/stateset/stateset-icommerce/bindings/go/stateset"
)
func main() {
commerce, _ := stateset.New("./store.db")
defer commerce.Close()
customer, _ := commerce.Customers().Create("alice@example.com", "Alice", "Smith", "")
product, _ := commerce.Products().Create("Widget", "SKU-001", 29.99, "")
items := []stateset.OrderItem{{ProductID: product.ID, SKU: "SKU-001", Name: "Widget", Quantity: 2, UnitPrice: "29.99"}}
order, _ := commerce.Orders().Create(customer.ID, items, "USD")
fmt.Printf("Order: %s\n", order.OrderNumber)
}CLI (AI-Powered)
Tip: ss is a shorthand alias for stateset.
# Natural language interface
stateset "show me pending orders"
stateset "what's my revenue this month?"
stateset "convert $100 USD to EUR"
# Execute operations (requires --apply)
stateset --apply "create a cart for alice@example.com"
stateset --apply "ship order #12345 with tracking FEDEX123"
stateset --apply "approve return RET-001"
# Tax calculation
stateset "calculate tax for an order shipping to California"
stateset "what's the VAT rate for Germany?"
# Promotions
stateset --apply "create a 20% off promotion called Summer Sale"
stateset "is coupon SAVE20 valid?"
stateset --apply "apply promotions to cart CART-123"
# Subscriptions
stateset "show me all subscription plans"
stateset --apply "create a monthly plan called Pro at $29.99"
stateset --apply "subscribe customer alice@example.com to the Pro plan"
# Payments & Refunds
stateset "list payments for order #12345"
stateset --apply "create payment for order #12345 amount $99.99 via card"
stateset --apply "refund payment PAY-001 amount $25.00"
# Shipments
stateset --apply "create shipment for order #12345 via FedEx tracking FEDEX123"
stateset --apply "mark shipment SHIP-001 as delivered"
# Supply Chain
stateset "list purchase orders"
stateset --apply "create purchase order for supplier SUP-001"
stateset --apply "approve purchase order PO-001"
# Invoices (B2B)
stateset "show overdue invoices"
stateset --apply "create invoice for customer CUST-001"
stateset --apply "record payment on invoice INV-001"
# Warranties
stateset "list warranties for customer CUST-001"
stateset --apply "create warranty for product SKU-001"
stateset --apply "file warranty claim for warranty WRN-001"
# Manufacturing
stateset "list bills of materials"
stateset --apply "create BOM for product WIDGET-ASSEMBLED"
stateset --apply "add component SKU-PART-A quantity 2 to BOM-001"
stateset --apply "create work order from BOM-001 quantity 50"
stateset --apply "complete work order WO-001 with 48 units produced"Agent-to-Agent (A2A) Commerce
AI agents can pay, quote, subscribe, and negotiate with each other autonomously.
# Direct agent-to-agent payment
stateset --apply "pay 10 USDC to 0x1234...5678 on Set Chain"
# Request payment from another agent
stateset --apply "request 50 USDC from 0xBuyer for API credits"
# Quotes β request, provide, accept
stateset --apply "request quote from data provider for 100 API credits"
stateset --apply "provide quote of $150 for premium data access"
stateset --apply "accept quote QT-001 and pay"
# Recurring subscriptions between agents
stateset --apply "create monthly subscription for 0xSubscriber at $49.99 with 14-day trial"
stateset "list active a2a subscriptions"
stateset --apply "pause a2a subscription SUB-001"
stateset --apply "cancel a2a subscription SUB-001"
# Split payments (multi-party)
stateset --apply "create split payment of $100: 70% to 0xSeller, 20% to 0xAffiliate, 10% platform fee"
stateset --apply "execute split payment SPLIT-001"
# Escrow with conditions
stateset --apply "create escrow payment of 100 USDC with condition seller_fulfilled"
stateset --apply "fulfill escrow condition on ESCROW-001"
stateset --apply "release escrow ESCROW-001"
# Agent discovery and trust
stateset "discover agents that can process payments on Set Chain"
stateset "find verified sellers with USDC support"
stateset "get reputation for agent 0xSeller"
# Webhook notifications
stateset --apply "configure webhook for agent 0xMyAgent to https://hooks.example.com/a2a"
stateset "list a2a notifications for agent 0xMyAgent"
# Event streaming
stateset --apply "subscribe to a2a_payment.* events"
stateset "get a2a event history for last 24 hours"Sync CLI (VES v1.0)
Verifiable Event Sync (VES) enables local SQLite databases to synchronize with the stateset-sequencer service, providing deterministic event ordering, conflict resolution, and cryptographic audit trails.
# Initialize sync for a store
stateset-sync init --sequencer-url grpc://sequencer.stateset.network:443 \
--tenant-id <uuid> --store-id <uuid> --api-key <key>
# Sync operations
stateset-sync push # Push pending events to sequencer
stateset-sync pull # Pull remote events locally
stateset-sync status # Show sync status
stateset-sync verify <event-id> # Verify event inclusion proof
stateset-sync rebase # Rebase after conflict
stateset-sync conflicts # List unresolved conflicts
stateset-sync history # Show sync history
# Key Management (Ed25519/X25519)
stateset-sync keys:generate # Generate signing and encryption keys
stateset-sync keys:list # List agent keys
stateset-sync keys:register # Register signing key with sequencer
stateset-sync keys:rotate --all --register # Rotate keys and re-register
stateset-sync keys:export # Export public keys for sharing
# Key Rotation Policies
stateset-sync keys:policy --key-type signing --max-age 720 --grace-period 72
stateset-sync keys:expiry # Check key expiration warnings
stateset-sync keys:batch-rotate --key-type all --register
# Encryption Groups (multi-agent)
stateset-sync groups:create --name "warehouse-agents"
stateset-sync groups:add-member --group-id <id> --agent-id <id>
stateset-sync groups:remove-member --group-id <id> --agent-id <id>
stateset-sync groups:list # List all groups
stateset-sync groups:show <id> # Show group details
stateset-sync groups:my-groups # List your group membershipsMessaging Channels CLI
Deploy AI commerce agents to 10 messaging platforms. Each channel runs as a thin adapter over the shared base module.
# Single-channel gateways
stateset-telegram --db ./store.db --agent customer-service
stateset-discord --db ./store.db --agent customer-service
stateset-slack --db ./store.db --agent customer-service
stateset-whatsapp --db ./store.db --agent customer-service
stateset-signal --db ./store.db --agent customer-service
stateset-google-chat --db ./store.db --agent customer-service
# Experimental channels
stateset-webchat --db ./store.db --port 3000
stateset-imessage --db ./store.db --agent customer-service
stateset-teams --db ./store.db --agent customer-service
stateset-matrix --db ./store.db --agent customer-service --homeserver matrix.example.com
# Multi-channel orchestrator (all channels in one process)
stateset-channels --config channels.yaml
# With autonomous engine notifications
stateset-autonomous --db ./store.db --agent customer-service \
--notify-config notify-config.jsonIn-chat bot commands (available on all channels):
/help β List available commands
/orders [n] β Show recent orders (default 5)
/order <id> β Order detail with rich card
/inventory <sku> β Stock levels with rich card
/cart [id] β Cart summary
/track <id> β Shipment tracking
/customers β Customer count
/analytics β Sales summary with rich card
/stats β Channel metrics (messages, response time, errors)
/whoami β Show linked customer identity
/link <email> β Link chat to a customer by email
/unlink β Remove customer link
/escalate [reason] β Hand off to a human agent
/release β Return conversation to AI bot
/reset β Reset session state
Example channels.yaml:
shared:
db: ./store.db
agent: customer-service
model: claude-sonnet-4-20250514
middleware:
rateLimiter: { maxPerMinute: 20 }
contentFilter: { action: warn }
logger: true
channels:
telegram:
token: ${TELEGRAM_BOT_TOKEN}
allowList: [-1001234567890]
discord:
token: ${DISCORD_BOT_TOKEN}
channelIds: ["1234567890123456"]
slack:
token: ${SLACK_BOT_TOKEN}
appToken: ${SLACK_APP_TOKEN}
channels: ["C01ABCDEF"]
notifications:
routes:
"order.shipped": [{ channel: slack, target: "#orders" }]
"inventory.low": [{ channel: slack, target: "#ops" }]
"*": [{ channel: slack, target: "#all-alerts" }]Skills CLI
Browse, install, and manage 38 commerce domain skills that enhance agent capabilities.
# List all loaded skills
stateset-skills list
# Search for skills
stateset-skills search "inventory"
# Install from marketplace
stateset-skills install commerce-warehouse
# Temporary migration mode for legacy catalogs without checksums
stateset-skills install commerce-warehouse --allow-insecure-downloads
# Uninstall a skill
stateset-skills uninstall commerce-warehouse
# Show skill details
stateset-skills info commerce-fulfillment
# List skill categories
stateset-skills categories
# Browse the marketplace
stateset-skills marketplace
# Health check all skills
stateset-skills doctorRemote installs are verified by checksum by default. For controlled migrations, you can opt out with --allow-insecure-downloads or STATESET_ALLOW_INSECURE_SKILL_DOWNLOADS=1.
Available skills: accounts-payable, accounts-receivable, analytics, autonomous-engine, autonomous-runbook, backorders, checkout, cost-accounting, credit, currency, customer-service, customers, embedded-sdk, engine-setup, events, fulfillment, general-ledger, inventory, invoices, lots-and-serials, manufacturing, mcp-tools, orders, payments, products, promotions, quality, receiving, returns, shipments, storefront, subscriptions, suppliers, sync, tax, vector-search, warehouse, warranties.
Daemon CLI
Manage the StateSet gateway as a background service with systemd integration.
# Start the gateway daemon
stateset-daemon start --config gateway.config.json
# Stop the daemon
stateset-daemon stop
# View logs
stateset-daemon logs --follow
# Health check
stateset-daemon health
# Tailscale VPN management
stateset-daemon tailscale up
stateset-daemon tailscale status
# SSH tunnel management
stateset-daemon tunnel add --host remote.example.com --port 8080
stateset-daemon tunnel list
stateset-daemon tunnel remove <name>Voice Mode
Hands-free chat with pluggable STT/TTS (ElevenLabs, OpenAI Whisper). Per-session settings + 30-min inactivity TTL β see the Key Features row for the full capability list.
stateset-chat --voice
stateset-chat --voice --tts-provider elevenlabs --stt-provider whisperMulti-Provider AI
Claude is the default with full MCP tool integration. OpenAI, Gemini,
and local Ollama work in chat-only mode. For embedded server-side
agents, use @stateset/embedded/* entrypoints (or
@stateset/embedded/agent-toolkit for advanced runtime controls).
stateset "ship order #12345" # Claude (default, full MCP)
stateset --provider openai "list orders" # chat-only
stateset --provider ollama --model llama3 "β¦" # local-onlyValidation & Errors
Inputs are validated at the repository layer (SKU format, required fields, currency codes, etc.) and errors include field-level context when possible.
use stateset_core::CommerceError;
match commerce.orders().create(order_input) {
Ok(order) => println!("created order {}", order.order_number),
Err(err) if err.is_validation() => {
eprintln!("validation error: {}", err);
}
Err(err) => {
eprintln!("unexpected error: {}", err);
}
}Order status updates enforce the core state machine (cancel before shipment, refund after delivery).
Production Notes
Security baseline for any non-loopback deployment (the server warns at startup when these are missing):
-
Authorization, not just authentication. Bearer auth is on by default,
but without an authz config any valid token has full access to every
/api/v1route. WireServerBuilder::with_authz(...)(RBAC roles, default-deny for unknown actors) so a leaked token has a scoped blast radius. -
Per-client rate limiting. Enable
ServerBuilder::with_rate_limit(rps, burst)β clients are keyed by peer IP with independent token buckets, so one abusive client cannot starve other tenants. -
Explicit CORS origins via
STATESET_HTTP_ALLOWED_ORIGINS(defaults cover local development only), and a/metricstoken or CIDR allowlist for scrape access.
Operational notes:
- Payments are recorded as ledger events; integrate a PCI-compliant PSP for capture and store tokens/last4 only.
- Sync is event-ordered and can surface conflicts; for order/payment state use a single writer or a sequenced event log.
- Treat external processor IDs and webhook IDs as idempotency keys and de-dupe on ingest to avoid double charges/refunds.
Domain Models
40 first-class domains, including: Orders, Customers, Products, Inventory, Carts, Payments, Returns, Shipments, Manufacturing, Purchase Orders, Warranties, Invoices, Currency, Analytics, Tax, Promotions, Subscriptions, Stablecoin, x402, A2A Commerce β plus the finance suite (General Ledger, Accounts Payable, Accounts Receivable, Fixed Assets, Revenue Recognition) and the warehouse suite (Warehouse, Fulfillment, Receiving, Cycle Counts, Work Orders, Quality, BOMs, Lots, Serials, Backorders).
Each domain ships with strongly-typed Rust models, generated language
bindings, MCP tool descriptors, and OpenAPI schemas. The authoritative
inventory lives in the OpenAPI spec
and the source crates under crates/stateset-core/src/models/.
Database Schema
60+ tables grouped into Core, Inventory, Financial, Fulfillment,
Manufacturing, Tax, Promotions, Subscriptions, A2A Commerce, and
Cross-cutting (warranties, carts, currency, event log). Migrations are
the authoritative source β see
crates/stateset-db/migrations/
for the full schema with indexes and foreign keys, and
docs/src/guides/dependency-direction.md
for how the schema layers map onto the Rust kernel.
MCP Tools
The MCP surface is generated from the live CLI registry instead of maintained as a static table in this README. For the exact current tool count, policy-domain breakdown, permissions summary, and full tool list, see the generated MCP Tool Inventory.
AI Agents
Specialized agents cover different commerce domains, including customer service, checkout, orders, inventory, analytics, sync, stablecoin payments, and multi-agent orchestration. The exact current agent count, descriptions, and tool access are generated from code in the Agent Inventory.
Key Features
A capability matrix β what ships in v1.0.x, with depth links. The agentic primitives that distinguish iCommerce from a generic commerce engine (A2A, x402, VES v1.0, Policy DSL, 898 MCP tools) are summarized in Why iCommerce and not duplicated here.
| Domain | Capabilities |
|---|---|
| Commerce | Order lifecycle (create β confirm β ship β deliver) Β· multi-location inventory with reservations Β· customer profiles Β· product catalog with variants/attributes |
| Financial | 35+ currencies (BTC, ETH, USDC included) Β· multi-method payments + refunds Β· invoice generation Β· supplier purchase orders Β· general ledger (journals, statements, period close, FX revaluation, month-end close) Β· AP (3-way match, payment runs, aging) Β· AR (collections, dunning, statements) Β· fixed-asset register with depreciation Β· ASC 606 revenue recognition |
| Tax | US/EU/Canada multi-jurisdiction calc Β· state/province auto-lookup Β· exemptions & certificates Β· EU VAT Β· CA GST/HST/PST |
| Promotions | %/fixed discounts Β· coupon codes with usage limits Β· BXGY Β· free shipping Β· time-limited campaigns |
| Subscriptions | Daily/weekly/monthly/annual plans Β· trial periods Β· pause/resume/cancel/skip Β· billing cycle management |
| Supply chain / WMS | Manufacturing BOMs Β· work orders with task tracking Β· carrier shipment tracking Β· RMA processing Β· fulfillment waves with pick/pack/ship Β· receiving + put-away Β· warehouse locations Β· cycle counts with variance application Β· lots + serials |
| Analytics | Sales summaries Β· demand forecast per SKU Β· revenue projections (with confidence intervals) Β· inventory health Β· customer LTV |
| A2A commerce | Direct agent-to-agent payments (USDC/USDT/ssUSD/DAI on SET Chain, Base, Ethereum, Arbitrum) Β· quote/negotiate Β· recurring subscriptions Β· split payments Β· escrow with conditional release Β· HMAC-signed webhooks Β· SSE event streaming Β· agent discovery + reputation. See AGENTIC_COMMERCE.md. |
| VES v1.0 | Local-first with sequencer sync Β· Ed25519 + ML-DSA-65 hybrid signatures Β· X25519 + ML-KEM-768 hybrid encryption Β· key rotation Β· encryption groups Β· Merkle proofs Β· conflict resolution (remote-wins/local-wins/merge). See PQC_INITIAL_SPEC.md. |
| Messaging | 10 platforms (WhatsApp, Telegram, Discord, Slack, Signal, Google Chat, WebChat, iMessage, Teams, Matrix) Β· SQLite-backed sessions Β· Koa-style middleware Β· rich messages (Embeds, Block Kit, HTML) Β· 15+ bot commands Β· proactive notifications Β· AIβhuman handoff |
| Skills system | 38 domain skills (AP/AR, fulfillment, quality, warehouse, cost accounting, credit, lots/serials, β¦) Β· skills marketplace for browse/install/manage |
| Voice mode | STT input + TTS output Β· pluggable providers (ElevenLabs, OpenAI Whisper) Β· 30-min inactivity TTL on per-session settings |
| Multi-provider AI | Claude (full MCP), OpenAI, Gemini, local Ollama Β· auto-detection Β· fallback chains. Non-Claude providers run chat-only. |
| Conversation memory | SQLite-backed across sessions Β· summaries + facts + token counts Β· keyword search Β· age-based auto-cleanup |
| Browser automation | CDP integration (no Puppeteer) Β· headless Chrome lifecycle Β· navigation, DOM, JS eval, screenshots β for scraping, storefront tests, catalog sync |
| Heartbeat monitor | 6 proactive checkers: low-stock, abandoned-carts, revenue-milestone, pending-returns, overdue-invoices, subscription-churn Β· EventBridge β channels Β· HTTP API for status / manual runs / enable+disable |
| Permission sandboxing | Bearer + query-param API keys Β· 6 levels: none < read < preview < write < delete < admin Β· sandbox mode blocks dangerous routes |
| AI-ready architecture | Deterministic operations Β· registry-generated MCP tool inventory Β· --apply write gate Β· event-driven full auditability Β· portable single-file state |
Installation
Per-language install commands and working code samples live under Quick Start above. The Language Bindings table immediately below summarizes every package and links to its docs. Platform-specific notes that don't fit either:
-
Java (Maven) β alternative to the Gradle line in the table:
<dependency> <groupId>com.stateset</groupId> <artifactId>embedded</artifactId> <version>1.24.0</version> </dependency>
-
PHP β after
composer require stateset/embedded, enable the native extension by runningcomposer install-extensionand addingextension=stateset_embeddedto yourphp.ini. Without the extension the autoloaded stubs throw at runtime. -
Swift β Swift Package Manager is the supported path. CocoaPods is community-maintained at
pod 'StateSet', '~> 1.24.0'. -
CLI β clone the repo, then
cd cli && npm install && npm link. After that,stateset --helpworks anywhere.
Language Bindings
StateSet provides a Rust SDK plus native runtime bindings built from the same Rust core:
| Language | Package | Install | Docs |
|---|---|---|---|
| Rust |
stateset-sdk / stateset-embedded
|
cargo add stateset-sdk --features full or stateset-embedded = "1.24.0"
|
docs.rs |
| Node.js | @stateset/embedded |
npm install @stateset/embedded@1.24.0 |
npm |
| Python | stateset-embedded |
pip install stateset-embedded |
PyPI |
| Ruby | stateset_embedded |
gem install stateset_embedded |
RubyGems |
| PHP | stateset/embedded |
composer require stateset/embedded |
Packagist |
| Java | com.stateset:embedded |
implementation 'com.stateset:embedded:1.24.0' |
Maven Central |
| Kotlin | com.stateset:embedded-kotlin |
implementation("com.stateset:embedded-kotlin:1.24.0") |
Maven Central |
| Swift | StateSet |
.package(url: "https://github.com/stateset/stateset-swift.git", from: "1.24.0") |
GitHub |
| C# / .NET | StateSet.Embedded |
dotnet add package StateSet.Embedded --version 1.24.0 / <PackageReference Include="StateSet.Embedded" Version="1.24.0" />
|
NuGet |
| Go | stateset |
go get github.com/stateset/stateset-icommerce/bindings/go/stateset@v1.24.0 |
pkg.go.dev |
| WASM | @stateset/embedded-wasm |
npm install @stateset/embedded-wasm |
npm |
For Rust specifically, stateset-sdk is the recommended facade crate. Use
stateset-embedded directly when you want the lower-level core commerce API
without the feature-gated SDK layer.
Platform Support
| Platform | Node.js | Python | Ruby | PHP | Java | Kotlin | Swift | C# | Go |
|---|---|---|---|---|---|---|---|---|---|
| Linux x86_64 | β | β | β | β | β | β | β | β | β |
| Linux arm64 | β | β | β | β | β | β | β | β | β |
| macOS x86_64 | β | β | β | β | β | β | β | β | β |
| macOS arm64 | β | β | β | β | β | β | β | β | β |
| Windows x86_64 | β | β | β | β | β | β | - | β | β |
| iOS | - | - | - | - | - | - | β | - | - |
| Android | - | - | - | - | β | β | - | - | - |
| Browser (WASM) | β | - | - | - | - | - | - | β * | - |
*Via Blazor WebAssembly
Framework Integration
Laravel (PHP)
// AppServiceProvider.php
$this->app->singleton(Commerce::class, fn() =>
new Commerce(storage_path('stateset/commerce.db'))
);Rails (Ruby)
# config/initializers/stateset.rb
Rails.application.config.stateset = StateSet::Commerce.new(
Rails.root.join('db', 'commerce.db').to_s
)Spring Boot (Java)
@Configuration
public class CommerceConfig {
@Bean(destroyMethod = "close")
public Commerce commerce() {
return new Commerce("commerce.db");
}
}Android (Kotlin)
// Application class
class CommerceApp : Application() {
val commerce by lazy {
StateSetCommerce(getDatabasePath("commerce.db").absolutePath)
}
}iOS/macOS (Swift)
// AppDelegate or @main struct
let commerce = try! StateSetCommerce(
path: FileManager.default
.urls(for: .documentDirectory, in: .userDomainMask)[0]
.appendingPathComponent("commerce.db").path
)ASP.NET Core (C#)
// Program.cs or Startup.cs
builder.Services.AddSingleton<StateSetCommerce>(sp =>
new StateSetCommerce("commerce.db"));Go (net/http or Gin)
// main.go
var commerce *stateset.Commerce
func init() {
var err error
commerce, err = stateset.New("commerce.db")
if err != nil {
log.Fatal(err)
}
}Configuration
Database Backends
SQLite (Default):
let commerce = Commerce::new("./store.db")?;
// Or in-memory for testing
let commerce = Commerce::new(":memory:")?;PostgreSQL:
let commerce = Commerce::with_postgres("postgres://user:pass@localhost/db")?;
// Or with options
let commerce = Commerce::builder()
.postgres("postgres://localhost/stateset")
.max_connections(20)
.build()?;CLI Environment
export ANTHROPIC_API_KEY=sk-ant-... # Required for AI mode
export STATESET_POLICY_DIR=./.stateset # Optional policy set directory (defaults to <db-path>/.stateset)
stateset --db ./store.db "list customers"Examples
# Run Rust examples
cargo run --example basic_usage
cargo run --example manufacturing
# CLI examples
stateset "how many orders do we have?"
stateset "what's the exchange rate from USD to EUR?"
stateset --apply "add 50 units to SKU-001"Development
Rust:
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test # Run the workspace Rust test suite
cargo bench -p stateset-benches # Criterion benchmarksBindings:
cd bindings/node && npm ci && npm test
cd bindings/python && python -m pip install maturin pytest && maturin develop --release && pytest -qCLI:
cd cli
npm test # All tests
npm run test:unit # Unit tests only
npm run test:integration # Integration tests
npm run test:e2e # End-to-end tests
npm run lint # ESLint
npm run typecheck # JSDoc type checking
npm run test:coverage # Coverage reportAdmin:
cd admin
npm test # Vitest test suiteProject Structure
stateset-icommerce/
βββ Cargo.toml # Workspace manifest
βββ crates/
β βββ stateset-primitives/ # Strongly-typed newtypes (OrderId, Sku, Money, CurrencyCode)
β βββ stateset-core/ # Domain models, services, repository traits
β βββ stateset-crypto/ # VES v1.0 (JCS, Ed25519, AES-256-GCM, Merkle)
β βββ stateset-db/ # Database layer (SQLite + PostgreSQL)
β βββ stateset-embedded/ # High-level embeddable commerce API
β βββ stateset-observability/ # Metrics + tracing helpers
β βββ stateset-macros/ # Proc macros
β βββ stateset-policy/ # Policy DSL engine (YAML, conditions, transforms)
β βββ stateset-http/ # Axum REST + SSE transport layer
β βββ stateset-a2a/ # Agent-to-Agent commerce
β βββ stateset-sync/ # Sync engine (outbox, conflict, transport)
β βββ stateset-authz/ # Authorization (RBAC, rate limiting, audit)
β βββ stateset-pricing/ # Deterministic pricing (line items, tax, FX)
β βββ stateset-migrations/ # SQL migrations (checksums, rollback)
β βββ stateset-jobs/ # Background jobs (cron, retries, backoff)
β βββ stateset-ffi/ # Stable C ABI (#[repr(C)], extern "C")
β βββ stateset-sdk/ # Facade re-exports + prelude
β βββ stateset-test-utils/ # Shared test fixtures & assertion macros
β βββ stateset-integration-tests/ # Cross-crate integration tests
β βββ stateset-benches/ # Criterion benchmarks
βββ bindings/
β βββ node/ # NAPI bindings (@stateset/embedded)
β βββ python/ # PyO3 bindings (stateset-embedded)
β βββ ruby/ # Magnus bindings (stateset_embedded gem)
β βββ php/ # ext-php-rs bindings (stateset/embedded)
β βββ java/ # JNI bindings (com.stateset:embedded)
β βββ kotlin/ # JNI bindings (com.stateset:embedded-kotlin)
β βββ swift/ # C FFI bindings (StateSet Swift package)
β βββ dotnet/ # P/Invoke bindings (StateSet.Embedded NuGet)
β βββ go/ # cgo bindings (stateset Go module)
β βββ wasm/ # WebAssembly bindings (@stateset/embedded-wasm)
βββ cli/
β βββ bin/ # CLI entry points
β βββ src/mcp-server.js # MCP orchestrator
β βββ src/tools/ # Modular tool modules
β βββ src/a2a/ # Agent-to-Agent commerce
β β βββ index.js # Direct payments, quotes, escrow, conditions
β β βββ store.js # SQLite persistence (7 tables)
β β βββ notifications.js # HMAC-SHA256 signed webhooks
β β βββ subscriptions.js # Recurring agent subscriptions
β β βββ splits.js # Multi-party split payments
β β βββ event-stream.js # SSE push, event log, subscriptions
β βββ src/channels/ # 10-channel messaging gateway
β βββ src/providers/ # Multi-provider AI (Claude, OpenAI, Gemini, Ollama)
β βββ src/voice/ # Voice mode (STT + TTS)
β βββ src/memory/ # Persistent conversation memory
β βββ src/browser/ # Chrome DevTools Protocol automation
β βββ src/skills/ # Skills loader, registry, marketplace
β βββ src/chains/ # Blockchain integration (Solana, Base, SET Chain, etc.)
β βββ src/x402/ # x402 AI agent payment protocol
β βββ src/imessage/ # iMessage gateway (BlueBubbles)
β βββ src/matrix/ # Matrix protocol gateway
β βββ src/teams/ # Microsoft Teams gateway (Bot Framework)
β βββ src/sync/ # VES sync engine
β β βββ engine.js # Sync orchestration
β β βββ outbox.js # Event outbox management
β β βββ client.js # gRPC sequencer client
β β βββ keys.js # Ed25519/X25519 key management
β β βββ groups.js # Encryption group management
β β βββ rotation-policy.js # Key rotation policies
β β βββ crypto.js # VES cryptographic operations
β β βββ conflict.js # Conflict resolution
β βββ skills/ # Commerce domain skills
β βββ deploy/ # Systemd services, Tailscale, SSH tunnels
β βββ .claude/ # AI agent definitions
βββ examples/
Current manifest-backed counts and topology live in Workspace Inventory.
Core Concepts
Agentic Commerce Protocol (ACP)
StateSet implements the Agentic Commerce Protocol, an open standard defining how AI agents perform commerce operations:
// ACP operations are deterministic and auditable
commerce.orders.create(...) // Create order
commerce.inventory.reserve(...) // Reserve stock
commerce.returns.approve(...) // Approve return
commerce.currency.convert(...) // Convert currencySafety Architecture
All write operations require explicit opt-in:
# Preview only (safe)
stateset "create a cart for alice@example.com"
# Actually execute (requires --apply)
stateset --apply "create a cart for alice@example.com"Event-Driven Architecture
All operations emit events for auditability:
pub enum CommerceEvent {
OrderCreated(Order),
OrderStatusChanged { id, from, to },
InventoryAdjusted { sku, delta, reason },
PaymentProcessed(Payment),
// ...
}Where this is going
The engine is the foundation; the goal is the kernel for agent-to-agent commerce on the open internet. The campaign β protocol completion and second-party adoption, trust graduation (audits, key rotation, staked reputation), compliance as first-class primitives, and a schedule for the remaining engineering debt β is laid out in KERNEL_ROADMAP.md.
License
MIT OR Apache-2.0
Contributing
Contributions welcome! Please read the contributing guidelines before submitting PRs.
Built with Rust for reliability, designed for AI agents.