Fundamentals
Getting Started with Business-as-Code
Build your first autonomous business in 15 minutes
This guide will help you build your first autonomous business using Business-as-Code in 15 minutes.
Prerequisites
- Node.js 18+ installed
- Basic TypeScript knowledge
- A code editor (VS Code recommended)
Installation
# Create a new project
mkdir my-first-business
cd my-first-business
npm init -y
# Install the SDK
npm install sdk.do
# Install TypeScript and dev dependencies
npm install -D typescript tsx @types/node# Create a new project
mkdir my-first-business
cd my-first-business
pnpm init
# Install the SDK
pnpm add sdk.do
# Install TypeScript and dev dependencies
pnpm add -D typescript tsx @types/node# Create a new project
mkdir my-first-business
cd my-first-business
bun init
# Install the SDK
bun add sdk.do
# Install TypeScript and dev dependencies
bun add -D typescript tsx @types/nodeThis tutorial takes about 15 minutes to complete. You'll learn core Business-as-Code concepts by building a real autonomous business.
Your First Business
Let's build a simple product catalog business with autonomous pricing.
Create the Business Entity
Create src/index.ts:
// @errors: 7006
import $, { db, on, send, ai } from 'sdk.do'
// Define your business organization
const business = await $.Organization.create({
// ^?
$type: 'Organization',
name: 'My Product Store',
description: 'An autonomous product catalog',
url: 'https://mystore.example.com',
})
console.log('Business created:', business.$id)
// ^?What's happening?
$.Organization.create()creates a semantic entity- The
$type: 'Organization'comes from Schema.org - AI models understand this is a business entity
- Returns a typed object with an
$id
Add Products
// Create a product with semantic metadata
const product = await $.Product.create({
$type: 'Product',
name: 'Wireless Mouse',
description: 'Ergonomic wireless mouse with long battery life',
brand: await $.Brand.create({ name: 'TechCo' }),
category: 'Electronics',
// Pricing information
offers: [
{
$type: 'Offer',
price: 29.99,
priceCurrency: 'USD',
availability: $.InStock,
seller: business,
},
],
// Custom business data
inventory: 100,
costPrice: 12.5,
})
// Relate product to business
await db.relate(business, $.sells, product)
console.log('Product created:', product.$id)What's happening?
- Products use Schema.org's Product type
- Offers embed pricing information
- Relationships are explicit: business → sells → product
- You can extend with custom properties (inventory, costPrice)
Add Event-Driven Logic
// Listen for product views
on.Product.viewed(async (event) => {
const { product, customer } = event
console.log(`${customer.name} viewed ${product.name}`)
// Track analytics
db.increment(product, $.analytics.views)
// AI recommends related products
const recommendations = await ai.recommend({
type: $.Product,
basedOn: product,
strategy: 'related',
limit: 3,
})
// Send recommendations to customer
send.Notification.send({
to: customer,
type: 'product-recommendations',
data: { recommendations },
})
})
// Handle orders
on.Order.created(async (order) => {
console.log('New order:', order.orderNumber)
// Process payment
const payment = await send.Payment.process({
amount: order.totalPrice,
currency: order.priceCurrency,
customer: order.customer,
})
if (payment.status === 'succeeded') {
// Update inventory
for (const item of order.orderedItem) {
db.Product.decrement(item.orderItem.$id, {
inventory: item.orderQuantity,
})
}
// Send confirmation
send.Email.send({
to: order.customer.email,
template: 'order-confirmation',
data: { order, payment },
})
// Fulfill order
send.Order.fulfill({ order })
} else {
send.Order.cancel({
order,
reason: 'payment-failed',
})
}
})What's happening?
on()registers event handlers for semantic events- Events trigger workflows automatically
- AI generates recommendations based on context
- Operations are asynchronous and composable
Add AI-Powered Features
// Dynamic pricing based on demand
async function updatePricing() {
const products = await db.Product.list()
for (const product of products) {
// Analyze demand
const metrics = await db.Order.analyze({
product: product.$id,
timeRange: '7d',
})
// AI decides optimal price
const decision = await ai.decide('dynamic-pricing', {
product,
currentPrice: product.offers[0].price,
costPrice: product.costPrice,
salesVolume: metrics.count,
inventory: product.inventory,
targetMargin: 0.4,
})
if (decision.shouldUpdate) {
// Update price
await db.Product.update(product.$id, {
offers: [
{
$type: 'Offer',
price: decision.recommendedPrice,
priceCurrency: 'USD',
availability: $.InStock,
priceValidUntil: decision.validUntil,
},
],
})
console.log(`Updated ${product.name}: $${product.offers[0].price} → $${decision.recommendedPrice}`)
}
}
}
// Run pricing updates every hour
setInterval(updatePricing, 3600000)What's happening?
- AI analyzes business metrics
- Makes pricing decisions based on multiple factors
- Updates prices autonomously
- Runs continuously in production
Run Your Business
// src/index.ts - Complete example
import $, { db, on, send, ai } from 'sdk.do'
async function main() {
// Create business
const business = await $.Organization.create({
$type: 'Organization',
name: 'My Product Store',
})
// Add products
const mouse = await $.Product.create({
$type: 'Product',
name: 'Wireless Mouse',
description: 'Ergonomic wireless mouse',
offers: [
{
$type: 'Offer',
price: 29.99,
priceCurrency: 'USD',
availability: $.InStock,
},
],
inventory: 100,
costPrice: 12.5,
})
await db.relate(business, $.sells, mouse)
// Register event handlers
on.Order.created(async (order) => {
console.log('Processing order:', order.orderNumber)
const payment = await send.Payment.process({
amount: order.totalPrice,
customer: order.customer,
})
if (payment.status === 'succeeded') {
send.Order.fulfill({ order })
}
})
// Start pricing optimization
setInterval(async () => {
const products = await db.Product.list()
for (const product of products) {
const decision = await ai.decide('dynamic-pricing', { product })
if (decision.shouldUpdate) {
await db.Product.update(product.$id, {
offers: [{ price: decision.recommendedPrice }],
})
}
}
}, 3600000)
console.log('Business is running!')
}
main().catch(console.error)Run it:
npx tsx src/index.tsComplete Example: Todo App as a Business
Let's build something more interactive - a todo app as a business:
import $, { db, on, send, ai } from 'sdk.do'
// Define the todo service
const service = await $.Service.create({
$type: 'Service',
name: 'Smart Todo Service',
description: 'AI-powered task management',
})
// Register a user
on.Person.registered(async (person) => {
// Create welcome tasks
const welcomeTasks = await ai.generate('welcome-tasks', {
user: person,
context: 'first-time-user',
})
for (const task of welcomeTasks) {
$.Action.create({
$type: 'Action',
name: task.name,
description: task.description,
agent: person,
actionStatus: 'PotentialActionStatus',
})
}
})
// Smart task creation
on.Action.created(async (action) => {
// AI analyzes task
const analysis = await ai.analyze('task-complexity', {
task: action,
})
// Suggest subtasks if complex
if (analysis.isComplex) {
const subtasks = await ai.generate('subtasks', {
task: action,
maxSubtasks: 5,
})
for (const subtask of subtasks) {
$.Action.create({
$type: 'Action',
name: subtask.name,
partOf: action,
agent: action.agent,
})
}
}
// Auto-schedule based on priority
const schedule = await ai.decide('task-scheduling', {
task: action,
existingTasks: await db.related(action.agent, $.hasAction, $.Action),
})
db.Action.update(action.$id, {
startTime: schedule.recommendedStart,
endTime: schedule.estimatedEnd,
})
})
// Task completion
on.Action.completed(async (action) => {
// Send celebration
send.Notification.send({
to: action.agent,
type: 'achievement',
message: `Great job completing "${action.name}"!`,
})
// Update user stats
db.increment(action.agent, $.stats.completedTasks)
// AI suggests next task
const nextTask = await ai.recommend({
type: $.Action,
for: action.agent,
context: 'next-action',
limit: 1,
})
if (nextTask) {
send.Notification.send({
to: action.agent,
type: 'suggestion',
message: `Ready for your next task: "${nextTask.name}"?`,
})
}
})Key Concepts Recap
1. Semantic Entities
Always use semantic types:
// Good: Semantic types
;($.Organization, $.Product, $.Person, $.Order)
// Avoid: Custom types when standard exists
;(User, Item, Company)2. Event-Driven
Business logic flows through events:
on.Event.happened(async (data) => {
// React to events
send.AnotherEvent(result)
})3. AI Integration
AI is native, not bolted on:
// AI understands your data
const result = await ai.decide('business-decision', context)
const content = await ai.generate('content-type', params)
const items = await ai.recommend({ type, for, context })4. Relationships
Model connections explicitly:
// Create relationship
await db.relate(subject, $.predicate, object)
// Query relationship
const results = await db.related(subject, $.predicate, $.Type)Next Steps
Now that you've built your first business, explore:
- Core Concepts - Deep dive into entities, events, and workflows
- Semantic Patterns - Master the $.Subject.predicate.Object pattern
- Autonomous Operations - Build self-operating businesses
- Workflow Patterns - Complex business processes
- Use Cases - Real-world examples
Common Patterns
CRUD Operations
// Create
const entity = await $.Type.create({
/* data */
})
// Read
const entity = await db.Type.get(id)
const entities = await db.Type.list({
where: {
/* query */
},
})
// Update
await db.Type.update(id, {
/* changes */
})
// Delete
await db.Type.delete(id)Relationships
// Create relationship
await db.relate(customer, $.places, order)
// Query forward
const orders = await db.related(customer, $.places, $.Order)
// Query inverse
const customer = await db.related(order, $.placedBy, $.Customer)Events
// Listen
on.Event.name(async (data) => {
// Handle event
})
// Emit
send.Event.name(data)AI Operations
// Generate content
const content = await ai.generate(type, context)
// Make decisions
const decision = await ai.decide(strategy, context)
// Get recommendations
const items = await ai.recommend({ type, for, context })
// Analyze data
const insights = await ai.analyze(metric, data)Troubleshooting
Resources
Next: Core Concepts →