xcomponent-ai
v0.6.0
Published
LLM-first framework for AI agents (Claude, GPT) to build apps with sanctuarized business logic. Event-driven FSM runtime with multi-instance state machines, cross-component communication, event sourcing, and production-ready persistence (PostgreSQL, Mongo
Maintainers
Readme
🤖 xcomponent-ai
xcomponent.ai
Business-first state machines with real-time monitoring, audit trails, and AI-safe execution
xcomponent-ai is a runtime for business-oriented state machines designed to make complex workflows observable, auditable, and controllable — even in distributed systems and AI-assisted architectures.
It provides:
- Declarative business logic defined in YAML
- A real-time monitoring UI
- A full audit trail with sequence diagrams
- Support for inter-machine orchestration
- Execution in a single runtime or distributed via Redis / RabbitMQ
👉 The goal: never lose business logic inside application code again.
Why xcomponent-ai exists
In large systems:
- Business rules are scattered across services
- Workflow behavior becomes implicit
- Debugging means reading logs and guessing
- AI-generated code increases the risk of losing control
xcomponent-ai makes business logic explicit, visible, and enforceable.
Core principles
Business logic is the source of truth
State machines define:
- allowed states
- valid transitions
- timeouts
- cross-machine interactions
Application code cannot bypass the model.
Observability is built-in
Every workflow instance is:
- visible in real time
- traceable from start to end
- explainable through its execution path
AI is an accelerator, not a decision-maker
LLMs can generate:
- APIs
- UIs
- integrations
But they must comply with the state machines. The business model is the guardrail.
xcomponent-ai separates what is durable (business logic in YAML) from what is disposable (implementation code generated by AI).
┌─────────────────────────────────────────────────────────────┐
│ 📋 YAML (Business Logic) │ 💻 Code (Implementation) │
│ ───────────────────────── │ ──────────────────────── │
│ • States and transitions │ • API routes │
│ • Compliance rules │ • UI components │
│ • Validation rules │ • External integrations │
│ • Approval workflows │ • Triggered methods │
│ │ │
│ ✅ Durable, auditable │ ♻️ Regenerable by LLM │
│ ✅ Version-controlled in Git │ ♻️ Easily adaptable │
│ ✅ Readable by non-developers │ │
└─────────────────────────────────────────────────────────────┘2️⃣ Monitoring UI – Official Description
Real-time Component Monitoring
The monitoring UI provides a live view of all components and their state machines.
Component overview
- Visual representation of all machines in a component
- Inter-machine transitions clearly displayed
- Entry points and terminal states highlighted

Instance tracking
For each machine:
- List of active instances
- Current state per instance
- Instance metadata and payload
- Filtering by state, ID, or data
Interactive execution
From the UI, you can:
- Manually trigger events
- Simulate transitions
- Drive workflows during debugging or recovery
- Observe immediate effects across machines
This is not just visualization — it is operational control.
Audit trail & sequence diagrams

For every instance:
- Full event history
- All transitions with timestamps
- Parent ↔ child machine interactions
- Sequence diagrams explaining how and why a state was reached
👉 This makes post-mortem analysis and compliance audits straightforward.
🎯 Who Is It For?
- Developers using LLMs (Claude, GPT) to generate code
- Teams who want to sanctuarize their business logic
- Enterprises with traceability and compliance requirements
📦 Installation
npm install -g xcomponent-aiRequirements: Node.js 20.0.0+
🚀 Quick Start
New to xcomponent-ai? → Read the Quick Start Guide for a 5-minute tutorial.
# Start runtime with dashboard
xcomponent-ai serve examples/trading.yaml
# Open browser → http://localhost:3000/dashboard.html
# Create instances, send events, visualize FSM in real-time!🤖 For LLMs (Claude, GPT, etc.)
xcomponent-ai is designed to be used by you (LLM) as a structuring framework for building applications with sanctuarized business logic.
Quick Pattern
When a developer asks you to build an application:
User: "Build a lending platform with credit checks and approval workflow"
LLM (You): I'll use xcomponent-ai to structure this with sanctuarized business logic.
1️⃣ Define FSM (immutable business logic):
fsm/loan-application.yaml → States, transitions, compliance rules
2️⃣ Initialize runtime:
src/runtime/index.ts → FSM runtime setup
3️⃣ Create API layer:
src/api/loan-routes.ts → HTTP → FSM events (thin wrapper)
4️⃣ Build UI:
src/ui/LoanForm.tsx → React components reading FSM state
Key principle: Business logic lives in YAML, code just connects to it.See LLM Framework Guide for complete usage patterns.
my-fintech-app/
├── fsm/ # 🔒 SANCTUARIZED (business logic)
│ ├── *.yaml # Immutable state machines
├── src/
│ ├── runtime/ # xcomponent-ai runtime
│ ├── api/ # HTTP → FSM events
│ └── ui/ # UI reading FSM state
└── tests/fsm/ # FSM simulation testsFor detailed guidance, see:
- LLM Framework Guide - Complete usage instructions for LLMs
- Full Project Example - E-commerce platform example
🚀 Quick Start
📖 Full guide: QUICKSTART.md
Two Ways to Use xcomponent-ai
1️⃣ Standalone CLI (Exploration)
npm install -g xcomponent-ai
xcomponent-ai load examples/trading.yaml2️⃣ Framework (Production Projects) ← Recommended
npx xcomponent-ai init my-fintech-app
cd my-fintech-app
npm install
# Edit fsm/*.yaml → build API/UIPrerequisites
- Node.js ≥ 20.0.0
- OpenAI API key (for AI agents):
export OPENAI_API_KEY=your_key
CLI Usage Examples
# Validate a component YAML file
xcomponent-ai validate examples/e-commerce-order/component.yaml
# Create FSM from natural language (AI-powered)
xcomponent-ai ai-create "Trading order with compliance checks for amounts over 100k" -o trading.yaml
# Load and inspect FSM
xcomponent-ai load examples/trading.yaml
# Run instance with events
xcomponent-ai run examples/payment.yaml Payment \
--context '{"accountBalance": 5000}' \
--events '[{"type":"AUTHORIZE_PAYMENT","payload":{"amount":100,"currency":"EUR","paymentMethod":"card"},"timestamp":1234567890}]'
# Simulate path
xcomponent-ai simulate examples/kyc.yaml Onboarding \
--events '[{"type":"DOCUMENTS_RECEIVED","payload":{"documentType":"passport"},"timestamp":123}]'
# Analyze logs with AI insights
xcomponent-ai ai-analyze TradingComponent
# Generate UI code
xcomponent-ai generate-ui examples/trading.yaml --type api -o generated-api.tsProgrammatic Usage
import { FSMRuntime, loadComponent, SupervisorAgent } from 'xcomponent-ai';
import * as yaml from 'yaml';
import * as fs from 'fs';
// Load component
const content = fs.readFileSync('examples/trading.yaml', 'utf-8');
const component = yaml.parse(content);
// Create runtime
const runtime = new FSMRuntime(component);
// Create instance
const instanceId = runtime.createInstance('OrderEntry', {
amount: 50000,
instrument: 'AAPL'
});
// Send event
await runtime.sendEvent(instanceId, {
type: 'VALIDATE',
payload: { amount: 50000, instrument: 'AAPL', clientId: 'C123' },
timestamp: Date.now(),
});
// AI Agent: Create FSM from description
const supervisor = new SupervisorAgent();
const result = await supervisor.getFSMAgent().createFSM(
'Payment workflow with SCA compliance and refund capability'
);
console.log(result.data.yaml);API Server
# Start API server
npm run api
# Visit dashboard: http://localhost:3000/dashboard.html
# WebSocket: ws://localhost:3000API endpoints:
POST /api/component/load- Load component from YAML filePOST /api/:component/:machine/instance- Create instancePOST /api/:component/instance/:instanceId/event- Send eventGET /api/:component/instance/:instanceId- Get instance stateGET /api/monitor/:component- Get monitoring dataPOST /api/ai/create-fsm- AI-powered FSM creationPOST /api/ai/analyze- AI log analysis
📊 Examples
Trading Workflow (examples/trading.yaml)
name: TradingComponent
stateMachines:
- name: OrderEntry
initialState: Pending
states:
- name: Pending
type: entry
- name: Validated
type: regular
- name: Executed
type: regular
- name: Settled
type: final
- name: Rejected
type: error
transitions:
- from: Pending
to: Validated
event: VALIDATE
triggeredMethod: validateOrderLimits
- from: Validated
to: Executed
event: EXECUTE
type: triggerable
- from: Executed
to: Settled
event: SETTLEMENT_COMPLETE
type: inter_machine # Instantiates Settlement machine
targetMachine: Settlement
- from: Pending
to: Rejected
event: TIMEOUT
type: timeout
timeoutMs: 30000Features demonstrated:
- Triggered methods for business validation
- Inter-machine transitions (Settlement)
- Timeout handling
- Error states
Order Processing with Property Matching (examples/order-processing-xcomponent.yaml)
Complete example demonstrating multi-instance routing:
// Create 100 concurrent orders
for (let i = 1; i <= 100; i++) {
runtime.createInstance('Order', {
Id: i,
AssetName: i % 2 === 0 ? 'AAPL' : 'GOOGL',
Quantity: 1000,
RemainingQuantity: 1000,
ExecutedQuantity: 0
});
}
// Execute specific order #42 (partial execution)
await runtime.broadcastEvent('Order', 'Pending', {
type: 'ExecutionInput',
payload: { OrderId: 42, Quantity: 500 },
timestamp: Date.now()
});
// Only Order #42 transitions to PartiallyExecuted
// Others remain in Pending stateFeatures demonstrated:
- Property-based instance routing (OrderId matching)
- Public member pattern (business object separation)
- Scalable multi-instance management (100+ orders)
KYC Workflow (examples/kyc.yaml)
Complete customer onboarding with:
- RGPD/GDPR consent checks
- AI document validation
- AML screening
- Manual review escalation
Payment Workflow (examples/payment.yaml)
PSD2-compliant payment processing with:
- Strong Customer Authentication (SCA)
- Refund capability (inter-machine)
- Timeout handling
🧠 Agentic AI Features
Supervisor Agent
Orchestrates specialized agents based on user intent:
const supervisor = new SupervisorAgent();
const result = await supervisor.processRequest(
'Create a KYC workflow with AML checks and GDPR compliance'
);FSM Agent
- Create FSM: Natural language → YAML
- Detect Missing Compliance: Suggests AML, KYC, RGPD checks
- Update FSM: Apply changes via prompts
- Simulate Paths: Test workflows before deployment
const fsmAgent = supervisor.getFSMAgent();
// Create
const result = await fsmAgent.createFSM('Payment with refund');
// Get compliance suggestions
console.log(result.suggestions);
// ["Consider adding AML/KYC compliance checks", ...]UI Agent
Generates Express routes and React components:
const uiAgent = supervisor.getUIAgent();
const apiCode = await uiAgent.generateAPIRoutes(component);
const reactCode = await uiAgent.generateReactUI(component);Monitoring Agent
Analyzes logs with natural language insights:
const monitoringAgent = supervisor.getMonitoringAgent();
const analysis = await monitoringAgent.analyzeLogs('TradingComponent');
// Insights:
// "Bottleneck detected: Validated->Executed takes 8.2s on average"
// "High error rate: 15.3%. Review error states and transitions."📡 Real-time Monitoring
WebSocket API
Subscribe to FSM events:
import io from 'socket.io-client';
const socket = io('http://localhost:3000');
// Subscribe to component
socket.emit('subscribe_component', 'TradingComponent');
// Listen to state changes
socket.on('state_change', (data) => {
console.log(`Instance ${data.instanceId}: ${data.previousState} → ${data.newState}`);
});
// Instance lifecycle
socket.on('instance_created', (instance) => { ... });
socket.on('instance_disposed', (instance) => { ... });
socket.on('instance_error', (error) => { ... });Dashboard
Visit http://localhost:3000/dashboard.html for:
- Active instances table
- Real-time event stream
- State visualizations
🏗️ Architecture
FSM Runtime
Built on @xstate/core with XComponent-inspired enhancements:
- Multi-instance management: Track unlimited concurrent instances
- Property matching: Automatic event routing to instances based on business properties
- Event-driven execution: Pub/Sub + WebSocket broadcasting
- Timeout transitions: Automatic timeouts with configurable delays
- Inter-machine workflows: Create new instances on transition
- Conditional transitions: Matching rules for event routing
See archi-runtime.mmd for sequence diagram.
Agentic Layer
graph TD
User[User Prompt] --> Supervisor[Supervisor Agent]
Supervisor --> FSM[FSM Agent]
Supervisor --> UI[UI Agent]
Supervisor --> Monitor[Monitoring Agent]
FSM --> |Create/Update| YAML[FSM YAML]
FSM --> |Detect| Compliance[Compliance Gaps]
UI --> |Generate| Code[Express/React Code]
Monitor --> |Analyze| Insights[Natural Language Insights]See archi-agents.mmd for detailed flow.
🎯 Property Matching & Multi-Instance Routing
XComponent-inspired property matching enables automatic event routing to instances based on business properties, eliminating manual instance ID tracking.
The Problem
In real-world applications, you often have many instances of the same state machine running simultaneously:
- 100+ active orders
- 1000+ customer KYC applications
- Dozens of concurrent trades
When an external event arrives, the system needs to find the correct instance to update.
The Solution
Property matching automatically routes events to instances where specified properties match:
transitions:
- from: Pending
to: Executed
event: ExecutionInput
matchingRules:
- eventProperty: OrderId # Property in event payload
instanceProperty: Id # Property in instance public memberHow it works:
- Event arrives:
{ OrderId: 42, Quantity: 500 } - System examines ALL
Orderinstances inPendingstate - For each instance, checks:
event.payload.OrderId === instance.publicMember.Id - Routes event ONLY to matching instances
- Other instances remain unaffected
Usage Example
import { FSMRuntime } from 'xcomponent-ai';
const runtime = new FSMRuntime(component);
// Create 100 orders
for (let i = 1; i <= 100; i++) {
runtime.createInstance('Order', {
Id: i,
AssetName: 'AAPL',
Quantity: 1000,
RemainingQuantity: 1000
});
}
// Execute specific order #42
const processedCount = await runtime.broadcastEvent('Order', 'Pending', {
type: 'ExecutionInput',
payload: { OrderId: 42, Quantity: 500 },
timestamp: Date.now()
});
console.log(`Processed ${processedCount} instances`); // 1
// Only Order #42 transitioned, others remain in PendingAdvanced Features
Nested Property Matching:
matchingRules:
- eventProperty: customer.id
instanceProperty: customerIdComparison Operators:
matchingRules:
- eventProperty: threshold
instanceProperty: balance
operator: '>' # Also: ===, !==, <, >=, <=Public Member Pattern (XComponent convention):
stateMachines:
- name: Order
publicMemberType: Order # Separates business object from internal stateBenefits
✅ No manual bookkeeping: No need to maintain external OrderId → InstanceId maps ✅ Survives restarts: When persistence is added, routing works automatically ✅ Decoupled: External systems don't need runtime internals ✅ Scalable: Handles 100-10,000 instances per state efficiently Contact: [email protected]
🧪 Testing
# Run all tests
npm test
# With coverage
npm test -- --coverage
# Watch mode
npm run test:watchCoverage target: >80% (branches, functions, lines, statements)
📚 Documentation
# Generate API docs
npm run doc
# Open docs/api/index.htmlGuides:
- Deployment Guide - All deployment modes (monolith, distributed, Redis, PostgreSQL)
- Distributed Dashboard Guide - Monitor external apps (Next.js, Express) with the dashboard
- Quick Start - Getting started in 5 minutes
- LLM Framework Guide - Complete usage for LLMs (Claude/GPT)
- Persistence Guide - Event sourcing and snapshot configuration
- Specification - Full framework specification
Deployment Examples:
- Monolith + PostgreSQL - Single process with database persistence
- Distributed + RabbitMQ - Multi-process with RabbitMQ bus
- Distributed + Redis - Multi-process with Redis bus
Business Examples:
- E-Commerce Order - Order processing with payment and shipping (Saga pattern)
- Approval Workflow - Multi-level approval with escalation
- Subscription Lifecycle - SaaS subscription management
Schema:
- JSON Schema - Validation schema for component YAML files
JSDoc coverage: All public APIs documented
🤝 Contributing
We welcome contributions! Please:
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Commit changes:
git commit -m 'Add my feature' - Push:
git push origin feature/my-feature - Open a Pull Request
Guidelines:
- Write tests (maintain >80% coverage)
- Follow TypeScript strict mode
- Add JSDoc comments
- Update README for new features
📄 License
Apache License 2.0 - see LICENSE
🙏 Acknowledgments
- Inspired by XComponent state machine architecture
- Built with LangChain.js
- Powered by XState
🔗 Links
- Documentation: API Docs
- Examples: examples/
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Built with ❤️ for secure fintech workflows
Reduce compliance risks. Accelerate development. Days → Minutes.
