npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

Readme

🤖 xcomponent-ai

npm version npm downloads CI Coverage License Node TypeScript

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

alt text


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

alt text

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-ai

Requirements: 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 tests

For detailed guidance, see:

🚀 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.yaml

2️⃣ Framework (Production Projects) ← Recommended

npx xcomponent-ai init my-fintech-app
cd my-fintech-app
npm install
# Edit fsm/*.yaml → build API/UI

Prerequisites

  • 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.ts

Programmatic 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:3000

API endpoints:

  • POST /api/component/load - Load component from YAML file
  • POST /api/:component/:machine/instance - Create instance
  • POST /api/:component/instance/:instanceId/event - Send event
  • GET /api/:component/instance/:instanceId - Get instance state
  • GET /api/monitor/:component - Get monitoring data
  • POST /api/ai/create-fsm - AI-powered FSM creation
  • POST /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: 30000

Features 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 state

Features 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 member

How it works:

  1. Event arrives: { OrderId: 42, Quantity: 500 }
  2. System examines ALL Order instances in Pending state
  3. For each instance, checks: event.payload.OrderId === instance.publicMember.Id
  4. Routes event ONLY to matching instances
  5. 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 Pending

Advanced Features

Nested Property Matching:

matchingRules:
  - eventProperty: customer.id
    instanceProperty: customerId

Comparison Operators:

matchingRules:
  - eventProperty: threshold
    instanceProperty: balance
    operator: '>'  # Also: ===, !==, <, >=, <=

Public Member Pattern (XComponent convention):

stateMachines:
  - name: Order
    publicMemberType: Order  # Separates business object from internal state

Benefits

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:watch

Coverage target: >80% (branches, functions, lines, statements)

📚 Documentation

# Generate API docs
npm run doc

# Open docs/api/index.html

Guides:

Deployment Examples:

Business Examples:

Schema:

  • JSON Schema - Validation schema for component YAML files

JSDoc coverage: All public APIs documented

🤝 Contributing

We welcome contributions! Please:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Commit changes: git commit -m 'Add my feature'
  4. Push: git push origin feature/my-feature
  5. 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

🔗 Links


Built with ❤️ for secure fintech workflows

Reduce compliance risks. Accelerate development. Days → Minutes.