.do
Reference

Types

Complete TypeScript type definitions for Business-as-Code

Complete reference for all TypeScript types and interfaces in the Business-as-Code framework.

BusinessFunction

A business function is a reusable, composable operation that can be executed independently or as part of a workflow.

interface BusinessFunction<TInput = any, TOutput = any> {
  id: string
  name: string
  description?: string
  input?: TInput
  output?: TOutput
  execute: (input: TInput) => Promise<TOutput> | TOutput
  metadata?: Record<string, any>
}

Properties

id

  • Type: string
  • Required: Yes
  • Description: Unique identifier for the function. Should be kebab-case and descriptive.
// ✅ Good IDs
id: 'calculate-discount'
id: 'send-welcome-email'
id: 'process-payment'

// ❌ Bad IDs
id: 'func1'
id: 'doStuff'

name

  • Type: string
  • Required: Yes
  • Description: Human-readable name for the function. Used in UIs and logs.
name: 'Calculate Discount'
name: 'Send Welcome Email'
name: 'Process Payment'

description

  • Type: string
  • Required: No
  • Description: Optional detailed description of what the function does.
description: 'Calculates the final price after applying a percentage discount'
description: 'Sends a welcome email to new users with onboarding information'

input

  • Type: TInput
  • Required: No
  • Description: Optional schema or example of the input type. Used for documentation and validation.
input: {
  price: 100,
  discountPercent: 10,
}

output

  • Type: TOutput
  • Required: No
  • Description: Optional schema or example of the output type. Used for documentation and validation.
output: {
  finalPrice: 90,
  saved: 10,
}

execute

  • Type: (input: TInput) => Promise<TOutput> | TOutput
  • Required: Yes
  • Description: The function implementation. Can be sync or async.
execute: async (input) => {
  // Implementation
  return result
}

metadata

  • Type: Record<string, any>
  • Required: No
  • Description: Optional metadata for the function (tags, owner, version, etc.)
metadata: {
  owner: 'engineering',
  version: '1.0.0',
  tags: ['finance', 'pricing'],
  deprecated: false,
}

Generic Types

BusinessFunction supports generic types for full type safety:

// Strongly typed function
const calculateTax: BusinessFunction<{ amount: number; taxRate: number }, { tax: number; total: number }> = {
  id: 'calculate-tax',
  name: 'Calculate Tax',
  execute: async ({ amount, taxRate }) => {
    const tax = amount * taxRate
    return { tax, total: amount + tax }
  },
}

// TypeScript infers the types
const result = await calculateTax.execute({ amount: 100, taxRate: 0.08 })
console.log(result.tax) // Type: number
console.log(result.total) // Type: number

Examples

Simple Function

const greet: BusinessFunction<{ name: string }, { message: string }> = {
  id: 'greet',
  name: 'Greet User',
  description: 'Returns a greeting message',
  execute: async ({ name }) => {
    return { message: `Hello, ${name}!` }
  },
}

const result = await greet.execute({ name: 'Alice' })
console.log(result.message) // "Hello, Alice!"

Function with External API

const sendEmail: BusinessFunction<{ to: string; subject: string; body: string }, { messageId: string; status: 'sent' | 'failed' }> = {
  id: 'send-email',
  name: 'Send Email',
  description: 'Sends an email via SendGrid',
  execute: async ({ to, subject, body }) => {
    const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        personalizations: [{ to: [{ email: to }] }],
        from: { email: '[email protected]' },
        subject,
        content: [{ type: 'text/plain', value: body }],
      }),
    })

    if (!response.ok) {
      return { messageId: '', status: 'failed' }
    }

    const data = await response.json()
    return { messageId: data.message_id, status: 'sent' }
  },
  metadata: {
    provider: 'sendgrid',
    category: 'communication',
  },
}

Function with Database

import { db, $ } from 'sdk.do'

const createUser: BusinessFunction<{ email: string; name: string }, { userId: string; created: Date }> = {
  id: 'create-user',
  name: 'Create User',
  execute: async ({ email, name }) => {
    const user = await db.create($.Person, {
      $type: 'Person',
      email,
      name,
      givenName: name.split(' ')[0],
      familyName: name.split(' ').slice(1).join(' '),
    })

    return {
      userId: user.$id,
      created: new Date(),
    }
  },
}

Function with Error Handling

const processPayment: BusinessFunction<
  { orderId: string; amount: number; paymentMethod: string },
  { transactionId: string; status: 'success' | 'failed'; error?: string }
> = {
  id: 'process-payment',
  name: 'Process Payment',
  execute: async ({ orderId, amount, paymentMethod }) => {
    try {
      // Call payment processor
      const result = await stripe.paymentIntents.create({
        amount: Math.round(amount * 100), // Convert to cents
        currency: 'usd',
        payment_method: paymentMethod,
        metadata: { orderId },
      })

      return {
        transactionId: result.id,
        status: 'success',
      }
    } catch (error) {
      return {
        transactionId: '',
        status: 'failed',
        error: error.message,
      }
    }
  },
}

BusinessWorkflow

A workflow is a coordinated sequence of steps that accomplishes a business objective.

interface BusinessWorkflow {
  id: string
  name: string
  description?: string
  steps: WorkflowStep[]
  triggers?: WorkflowTrigger[]
  metadata?: Record<string, any>
}

Properties

id

  • Type: string
  • Required: Yes
  • Description: Unique identifier for the workflow.
id: 'user-onboarding'
id: 'order-fulfillment'
id: 'invoice-processing'

name

  • Type: string
  • Required: Yes
  • Description: Human-readable name for the workflow.
name: 'User Onboarding'
name: 'Order Fulfillment'
name: 'Invoice Processing'

description

  • Type: string
  • Required: No
  • Description: Optional detailed description of what the workflow does.
description: 'Onboards new users by sending welcome email, assigning a rep, and creating initial tasks'

steps

  • Type: WorkflowStep[]
  • Required: Yes
  • Description: Array of steps in the workflow. See WorkflowStep for details.
steps: [
  {
    id: 'send-email',
    name: 'Send Welcome Email',
    type: 'function',
    function: 'send-welcome-email',
    next: 'assign-rep',
  },
  {
    id: 'assign-rep',
    name: 'Assign Sales Rep',
    type: 'agent',
    config: { agentRole: 'sdr' },
  },
]

triggers

  • Type: WorkflowTrigger[]
  • Required: No
  • Description: Optional array of triggers that start the workflow. See WorkflowTrigger for details.
triggers: [
  {
    type: 'event',
    config: { eventType: 'user.created' },
  },
]

metadata

  • Type: Record<string, any>
  • Required: No
  • Description: Optional metadata for the workflow.
metadata: {
  owner: 'sales',
  version: '2.1.0',
  sla: '24h',
}

Examples

Simple Workflow

const orderProcessing: BusinessWorkflow = {
  id: 'process-order',
  name: 'Process Order',
  description: 'Validates, charges, and fulfills an order',
  steps: [
    {
      id: 'validate',
      name: 'Validate Order',
      type: 'function',
      function: 'validate-order',
      next: 'charge',
    },
    {
      id: 'charge',
      name: 'Charge Payment',
      type: 'function',
      function: 'process-payment',
      next: 'fulfill',
    },
    {
      id: 'fulfill',
      name: 'Fulfill Order',
      type: 'function',
      function: 'create-fulfillment',
    },
  ],
  triggers: [
    {
      type: 'event',
      config: { eventType: 'order.created' },
    },
  ],
}

Conditional Workflow

const leadRouting: BusinessWorkflow = {
  id: 'route-lead',
  name: 'Route Lead',
  description: 'Routes leads based on value and geography',
  steps: [
    {
      id: 'check-value',
      name: 'Check Lead Value',
      type: 'condition',
      condition: 'input.estimatedValue > 10000',
      next: ['enterprise-rep', 'standard-rep'],
    },
    {
      id: 'enterprise-rep',
      name: 'Assign Enterprise Rep',
      type: 'agent',
      config: { agentRole: 'enterprise-sdr' },
    },
    {
      id: 'standard-rep',
      name: 'Assign Standard Rep',
      type: 'agent',
      config: { agentRole: 'sdr' },
    },
  ],
}

Parallel Workflow

const productLaunch: BusinessWorkflow = {
  id: 'launch-product',
  name: 'Launch Product',
  description: 'Coordinates product launch across teams',
  steps: [
    {
      id: 'prepare',
      name: 'Prepare Launch',
      type: 'function',
      function: 'prepare-launch',
      next: ['marketing', 'sales', 'support'],
    },
    {
      id: 'marketing',
      name: 'Marketing Campaign',
      type: 'parallel',
      config: {
        steps: ['create-content', 'schedule-emails', 'update-website'],
      },
    },
    {
      id: 'sales',
      name: 'Sales Enablement',
      type: 'parallel',
      config: {
        steps: ['train-team', 'update-materials', 'set-quotas'],
      },
    },
    {
      id: 'support',
      name: 'Support Preparation',
      type: 'parallel',
      config: {
        steps: ['update-docs', 'train-agents', 'create-tickets'],
      },
    },
  ],
}

Human-in-the-Loop Workflow

const expenseApproval: BusinessWorkflow = {
  id: 'approve-expense',
  name: 'Expense Approval',
  description: 'Routes expenses for approval based on amount',
  steps: [
    {
      id: 'check-amount',
      name: 'Check Amount',
      type: 'condition',
      condition: 'input.amount > 1000',
      next: ['manager-approval', 'auto-approve'],
    },
    {
      id: 'manager-approval',
      name: 'Manager Approval',
      type: 'human',
      config: {
        approver: 'manager',
        timeout: '48h',
        escalation: 'director',
      },
      next: 'process-expense',
    },
    {
      id: 'auto-approve',
      name: 'Auto Approve',
      type: 'function',
      function: 'approve-expense',
      next: 'process-expense',
    },
    {
      id: 'process-expense',
      name: 'Process Expense',
      type: 'function',
      function: 'process-expense',
    },
  ],
}

WorkflowStep

A step is an individual unit of work in a workflow.

interface WorkflowStep {
  id: string
  name: string
  type: 'function' | 'condition' | 'parallel' | 'loop' | 'human' | 'agent'
  function?: string | BusinessFunction
  condition?: string
  next?: string | string[]
  config?: Record<string, any>
}

Properties

id

  • Type: string
  • Required: Yes
  • Description: Unique identifier for the step within the workflow.
id: 'send-email'
id: 'check-inventory'
id: 'approve-request'

name

  • Type: string
  • Required: Yes
  • Description: Human-readable name for the step.
name: 'Send Welcome Email'
name: 'Check Inventory Levels'
name: 'Approve Purchase Request'

type

  • Type: 'function' | 'condition' | 'parallel' | 'loop' | 'human' | 'agent'
  • Required: Yes
  • Description: The type of step to execute.

Step Types:

  • function: Execute a business function
  • condition: Branch based on a condition
  • parallel: Execute multiple steps concurrently
  • loop: Repeat steps based on a condition
  • human: Require human approval or input
  • agent: Delegate to an autonomous agent

function

  • Type: string | BusinessFunction
  • Required: For type: 'function' only
  • Description: The function to execute. Can be a function ID (string) or a full BusinessFunction object.
// Using function ID
function: 'send-email'

// Using inline function
function: {
  id: 'send-email',
  name: 'Send Email',
  execute: async (input) => {
    // Implementation
  }
}

condition

  • Type: string
  • Required: For type: 'condition' only
  • Description: JavaScript expression that evaluates to true/false. Has access to input variable.
condition: 'input.amount > 1000'
condition: 'input.user.role === "admin"'
condition: 'input.items.length > 0'

next

  • Type: string | string[]
  • Required: No
  • Description: The next step(s) to execute after this step completes.
// Single next step
next: 'send-confirmation'

// Multiple next steps (parallel execution)
next: ['notify-sales', 'notify-support']

// No next step (end workflow)
next: undefined

config

  • Type: Record<string, any>
  • Required: No
  • Description: Step-specific configuration. Content varies by step type.
// For function steps
config: {
  timeout: 5000,
  retries: 3,
}

// For agent steps
config: {
  agentRole: 'sdr',
  permissions: ['read', 'write'],
}

// For human steps
config: {
  approver: 'manager',
  timeout: '24h',
  escalation: 'director',
}

Step Types in Detail

Function Step

Executes a business function:

{
  id: 'calculate-total',
  name: 'Calculate Order Total',
  type: 'function',
  function: 'calculate-total',
  next: 'process-payment',
  config: {
    timeout: 5000,
    retries: 3,
  }
}

Condition Step

Branches based on a condition:

{
  id: 'check-inventory',
  name: 'Check Inventory',
  type: 'condition',
  condition: 'input.quantity <= inventory.available',
  next: ['in-stock', 'out-of-stock'],
  // If condition is true, go to first item in next array
  // If condition is false, go to second item in next array
}

Parallel Step

Executes multiple steps concurrently:

{
  id: 'notify-all',
  name: 'Notify All Teams',
  type: 'parallel',
  config: {
    steps: [
      'notify-sales',
      'notify-support',
      'notify-marketing'
    ],
    waitForAll: true  // Wait for all to complete
  },
  next: 'finalize'
}

Loop Step

Repeats steps based on a condition:

{
  id: 'process-items',
  name: 'Process All Items',
  type: 'loop',
  condition: 'items.length > 0',
  config: {
    iterator: 'items',
    step: 'process-single-item',
    maxIterations: 100
  },
  next: 'complete'
}

Human Step

Requires human approval or input:

{
  id: 'manager-approval',
  name: 'Manager Approval Required',
  type: 'human',
  config: {
    approver: 'manager',
    timeout: '48h',
    escalation: 'director',
    notificationChannel: 'email',
    approvalForm: {
      fields: ['approve', 'reject', 'comments']
    }
  },
  next: 'process-approval'
}

Agent Step

Delegates to an autonomous agent:

{
  id: 'qualify-lead',
  name: 'Qualify Lead',
  type: 'agent',
  config: {
    agentRole: 'sdr',
    permissions: ['read:leads', 'write:leads'],
    tools: ['search-company', 'enrich-contact'],
    maxIterations: 5,
    successCriteria: 'lead.score > 70'
  },
  next: 'route-lead'
}

Examples

Sequential Steps

const steps: WorkflowStep[] = [
  {
    id: 'step-1',
    name: 'First Step',
    type: 'function',
    function: 'step-one',
    next: 'step-2',
  },
  {
    id: 'step-2',
    name: 'Second Step',
    type: 'function',
    function: 'step-two',
    next: 'step-3',
  },
  {
    id: 'step-3',
    name: 'Third Step',
    type: 'function',
    function: 'step-three',
  },
]

Conditional Branching

const steps: WorkflowStep[] = [
  {
    id: 'check-value',
    name: 'Check Deal Value',
    type: 'condition',
    condition: 'input.value > 50000',
    next: ['enterprise-flow', 'standard-flow'],
  },
  {
    id: 'enterprise-flow',
    name: 'Enterprise Sales Process',
    type: 'function',
    function: 'enterprise-sales',
  },
  {
    id: 'standard-flow',
    name: 'Standard Sales Process',
    type: 'function',
    function: 'standard-sales',
  },
]

Error Handling

const steps: WorkflowStep[] = [
  {
    id: 'charge-card',
    name: 'Charge Credit Card',
    type: 'function',
    function: 'process-payment',
    config: {
      retries: 3,
      retryDelay: 1000,
      onError: 'handle-payment-error',
    },
    next: 'confirm-order',
  },
  {
    id: 'handle-payment-error',
    name: 'Handle Payment Error',
    type: 'function',
    function: 'payment-error-handler',
    next: 'notify-customer',
  },
]

WorkflowTrigger

A trigger defines when and how a workflow should be started.

interface WorkflowTrigger {
  type: 'schedule' | 'event' | 'webhook' | 'manual'
  config: Record<string, any>
  condition?: string
}

Properties

type

  • Type: 'schedule' | 'event' | 'webhook' | 'manual'
  • Required: Yes
  • Description: The type of trigger.

Trigger Types:

  • schedule: Run on a schedule (cron)
  • event: Run when an event occurs
  • webhook: Run when webhook receives request
  • manual: Run only when manually invoked

config

  • Type: Record<string, any>
  • Required: Yes
  • Description: Trigger-specific configuration. Content varies by type.

condition

  • Type: string
  • Required: No
  • Description: Optional condition that must be true for trigger to activate.

Trigger Types in Detail

Schedule Trigger

Runs on a schedule using cron syntax:

{
  type: 'schedule',
  config: {
    cron: '0 9 * * 1',  // Every Monday at 9 AM
    timezone: 'America/New_York'
  },
  condition: 'isBusinessDay()'
}

Common Cron Patterns:

'*/5 * * * *' // Every 5 minutes
'0 * * * *' // Every hour
'0 9 * * *' // Every day at 9 AM
'0 9 * * 1' // Every Monday at 9 AM
'0 0 1 * *' // First day of every month
'0 0 * * 0' // Every Sunday at midnight

Event Trigger

Runs when a specific event occurs:

{
  type: 'event',
  config: {
    eventType: 'user.created',
    source: 'auth-service'
  },
  condition: 'event.data.emailVerified === true'
}

Common Event Types:

'user.created'
'user.updated'
'order.created'
'order.completed'
'payment.succeeded'
'payment.failed'
'lead.created'
'deal.won'

Webhook Trigger

Runs when a webhook endpoint receives a request:

{
  type: 'webhook',
  config: {
    path: '/webhooks/stripe',
    method: 'POST',
    authentication: 'signature',
    signatureHeader: 'stripe-signature'
  },
  condition: 'body.type === "payment_intent.succeeded"'
}

Manual Trigger

Runs only when manually invoked:

{
  type: 'manual',
  config: {
    requiresApproval: true,
    approvers: ['admin', 'manager']
  }
}

Examples

Multiple Triggers

A workflow can have multiple triggers:

const workflow: BusinessWorkflow = {
  id: 'send-digest',
  name: 'Send Daily Digest',
  triggers: [
    {
      type: 'schedule',
      config: { cron: '0 9 * * *' }, // Daily at 9 AM
    },
    {
      type: 'manual',
      config: {}, // Can also be triggered manually
    },
  ],
  steps: [
    /* ... */
  ],
}

Conditional Trigger

Only trigger when condition is met:

{
  type: 'event',
  config: {
    eventType: 'order.created'
  },
  condition: 'event.data.total > 1000'  // Only for large orders
}

BusinessAgent

An agent is an autonomous entity that can execute functions and workflows.

interface BusinessAgent {
  id: string
  name: string
  description?: string
  role: 'cfo' | 'cmo' | 'cto' | 'swe' | 'sdr' | 'bdr' | 'custom'
  functions: string[] | BusinessFunction[]
  workflows?: string[] | BusinessWorkflow[]
  capabilities?: string[]
  config?: Record<string, any>
}

Properties

id

  • Type: string
  • Required: Yes
  • Description: Unique identifier for the agent.
id: 'sales-agent-1'
id: 'cfo-agent'
id: 'lead-qualifier'

name

  • Type: string
  • Required: Yes
  • Description: Human-readable name for the agent.
name: 'Sales Development Rep'
name: 'Chief Financial Officer'
name: 'Lead Qualification Agent'

description

  • Type: string
  • Required: No
  • Description: Optional description of the agent's purpose.
description: 'Qualifies inbound leads and schedules discovery calls'

role

  • Type: 'cfo' | 'cmo' | 'cto' | 'swe' | 'sdr' | 'bdr' | 'custom'
  • Required: Yes
  • Description: The agent's role or function in the organization.

Built-in Roles:

  • cfo: Chief Financial Officer - Financial operations
  • cmo: Chief Marketing Officer - Marketing operations
  • cto: Chief Technology Officer - Technical operations
  • swe: Software Engineer - Development tasks
  • sdr: Sales Development Rep - Inbound lead qualification
  • bdr: Business Development Rep - Outbound prospecting
  • custom: Custom role

functions

  • Type: string[] | BusinessFunction[]
  • Required: Yes
  • Description: Functions the agent can execute. Can be function IDs or full function objects.
// Using function IDs
functions: ['qualify-lead', 'schedule-call', 'send-email']

// Using function objects
functions: [
  {
    id: 'qualify-lead',
    name: 'Qualify Lead',
    execute: async (input) => {
      /* ... */
    },
  },
]

workflows

  • Type: string[] | BusinessWorkflow[]
  • Required: No
  • Description: Workflows the agent can run. Can be workflow IDs or full workflow objects.
workflows: ['lead-qualification', 'discovery-call-scheduling']

capabilities

  • Type: string[]
  • Required: No
  • Description: List of capabilities or skills the agent has.
capabilities: ['Lead qualification', 'Email communication', 'Calendar management', 'CRM data entry', 'Company research']

config

  • Type: Record<string, any>
  • Required: No
  • Description: Agent-specific configuration.
config: {
  model: 'gpt-5',
  temperature: 0.7,
  maxIterations: 10,
  tools: ['web-search', 'company-lookup'],
  permissions: ['read:leads', 'write:leads', 'read:accounts'],
}

Examples

Sales Development Rep

const sdrAgent: BusinessAgent = {
  id: 'sdr-1',
  name: 'Sales Development Rep',
  description: 'Qualifies inbound leads and schedules discovery calls',
  role: 'sdr',
  functions: ['qualify-lead', 'enrich-contact', 'schedule-call', 'send-email', 'update-crm'],
  workflows: ['lead-qualification', 'discovery-call-scheduling'],
  capabilities: ['Lead qualification', 'Needs assessment', 'Calendar management', 'Email communication', 'CRM data entry'],
  config: {
    model: 'gpt-5',
    temperature: 0.7,
    maxConcurrentLeads: 10,
    qualificationCriteria: {
      minCompanySize: 50,
      targetIndustries: ['Technology', 'Healthcare', 'Finance'],
      budgetThreshold: 50000,
    },
  },
}

Marketing Operations Agent

const cmoAgent: BusinessAgent = {
  id: 'cmo-agent',
  name: 'Chief Marketing Officer',
  description: 'Manages marketing campaigns and analyzes performance',
  role: 'cmo',
  functions: ['create-campaign', 'analyze-performance', 'optimize-spend', 'generate-content', 'schedule-posts'],
  workflows: ['campaign-launch', 'performance-review', 'content-calendar'],
  capabilities: ['Campaign management', 'Performance analysis', 'Budget optimization', 'Content generation', 'Social media management'],
  config: {
    channels: ['email', 'social', 'ads', 'content'],
    budget: 100000,
    goals: {
      leads: 1000,
      conversions: 100,
      revenue: 500000,
    },
  },
}

Software Engineer Agent

const sweAgent: BusinessAgent = {
  id: 'swe-1',
  name: 'Software Engineer',
  description: 'Writes and reviews code, fixes bugs',
  role: 'swe',
  functions: ['write-code', 'review-pr', 'fix-bug', 'write-tests', 'deploy-code'],
  workflows: ['feature-development', 'bug-fix', 'code-review'],
  capabilities: ['TypeScript/JavaScript', 'React', 'Node.js', 'Git', 'Testing', 'CI/CD'],
  config: {
    model: 'gpt-5',
    codeStyle: 'airbnb',
    testFramework: 'vitest',
    deployTarget: 'cloudflare-workers',
  },
}

Custom Agent

const customAgent: BusinessAgent = {
  id: 'invoice-processor',
  name: 'Invoice Processing Agent',
  description: 'Automates invoice processing and payment',
  role: 'custom',
  functions: ['extract-invoice-data', 'validate-invoice', 'match-purchase-order', 'schedule-payment', 'update-accounting'],
  workflows: ['invoice-processing', 'payment-scheduling'],
  capabilities: ['OCR/Document parsing', 'Data validation', 'PO matching', 'Payment scheduling', 'Accounting system integration'],
  config: {
    ocrProvider: 'google-vision',
    accountingSystem: 'quickbooks',
    approvalThreshold: 5000,
    paymentTerms: 'net-30',
  },
}

BusinessResource

A resource represents an entity or noun in the business domain.

interface BusinessResource {
  $id: string
  $type: string
  [key: string]: any
}

Properties

$id

  • Type: string
  • Required: Yes
  • Description: Unique identifier for the resource. Should be a URI or unique string.
$id: 'https://example.com/people/john-doe'
$id: 'user:12345'
$id: 'order:ORD-2024-001'

$type

  • Type: string
  • Required: Yes
  • Description: The type of resource. Should use Schema.org types when possible.
$type: 'Person'
$type: 'Organization'
$type: 'Product'
$type: 'Order'

Additional Properties

Resources can have any additional properties based on their type:

{
  $id: 'person:123',
  $type: 'Person',
  name: 'John Doe',
  email: '[email protected]',
  // ... any other properties
}

Examples

Person Resource

const person: BusinessResource = {
  $id: 'https://example.com/people/john-doe',
  $type: 'Person',
  name: 'John Doe',
  givenName: 'John',
  familyName: 'Doe',
  email: '[email protected]',
  telephone: '+1-555-0123',
  jobTitle: 'Software Engineer',
  worksFor: {
    $type: 'Organization',
    name: 'Acme Corp',
  },
}

Organization Resource

const organization: BusinessResource = {
  $id: 'https://example.com/orgs/acme-corp',
  $type: 'Organization',
  name: 'Acme Corp',
  legalName: 'Acme Corporation LLC',
  url: 'https://acme.com',
  email: '[email protected]',
  telephone: '+1-555-ACME',
  address: {
    $type: 'PostalAddress',
    streetAddress: '123 Main St',
    addressLocality: 'Austin',
    addressRegion: 'TX',
    postalCode: '78701',
    addressCountry: 'US',
  },
  numberOfEmployees: 500,
  foundingDate: '2015-01-01',
}

Product Resource

const product: BusinessResource = {
  $id: 'https://example.com/products/widget-pro',
  $type: 'Product',
  name: 'Widget Pro',
  description: 'Professional widget for enterprise use',
  brand: {
    $type: 'Brand',
    name: 'Acme Widgets',
  },
  offers: {
    $type: 'Offer',
    price: 99.99,
    priceCurrency: 'USD',
    availability: 'InStock',
  },
  category: 'Software',
  sku: 'WIDGET-PRO-001',
}

Order Resource

const order: BusinessResource = {
  $id: 'https://example.com/orders/ORD-2024-001',
  $type: 'Order',
  orderNumber: 'ORD-2024-001',
  orderStatus: 'Processing',
  orderDate: '2024-10-27T10:00:00Z',
  customer: {
    $type: 'Person',
    name: 'Jane Smith',
    email: '[email protected]',
  },
  orderedItem: [
    {
      $type: 'OrderItem',
      orderQuantity: 2,
      orderedItem: {
        $type: 'Product',
        name: 'Widget Pro',
      },
    },
  ],
  totalPrice: 199.98,
  priceCurrency: 'USD',
}

BusinessAction

An action represents a Subject-Verb-Object operation in the system.

interface BusinessAction {
  id: string
  verb: string
  subject: string | BusinessResource
  object?: string | BusinessResource
  timestamp?: string
  status?: 'pending' | 'in_progress' | 'completed' | 'failed'
  context?: Record<string, any>
}

Properties

id

  • Type: string
  • Required: Yes
  • Description: Unique identifier for the action.
id: 'action-123'
id: 'user-login-456'
id: 'order-create-789'

verb

  • Type: string
  • Required: Yes
  • Description: The action verb (what is being done).
verb: 'create'
verb: 'update'
verb: 'delete'
verb: 'send'
verb: 'process'

subject

  • Type: string | BusinessResource
  • Required: Yes
  • Description: Who or what is performing the action. Can be an ID or full resource.
subject: 'user:123'

// Or full resource
subject: {
  $id: 'user:123',
  $type: 'Person',
  name: 'John Doe',
}

object

  • Type: string | BusinessResource
  • Required: No
  • Description: What the action is being performed on. Can be an ID or full resource.
object: 'order:456'

// Or full resource
object: {
  $id: 'order:456',
  $type: 'Order',
  orderNumber: 'ORD-2024-001',
}

timestamp

  • Type: string
  • Required: No
  • Description: When the action occurred or will occur (ISO 8601 format).
timestamp: '2024-10-27T10:00:00Z'

status

  • Type: 'pending' | 'in_progress' | 'completed' | 'failed'
  • Required: No
  • Description: Current status of the action.
status: 'pending'
status: 'in_progress'
status: 'completed'
status: 'failed'

context

  • Type: Record<string, any>
  • Required: No
  • Description: Additional context or metadata for the action.
context: {
  ipAddress: '192.168.1.1',
  userAgent: 'Mozilla/5.0...',
  reason: 'User requested',
}

Examples

User Creates Order

const action: BusinessAction = {
  id: 'action-001',
  verb: 'create',
  subject: {
    $id: 'user:123',
    $type: 'Person',
    name: 'John Doe',
  },
  object: {
    $id: 'order:456',
    $type: 'Order',
    orderNumber: 'ORD-2024-001',
    totalPrice: 199.98,
  },
  timestamp: '2024-10-27T10:00:00Z',
  status: 'completed',
  context: {
    channel: 'web',
    source: 'checkout-page',
  },
}

Agent Sends Email

const action: BusinessAction = {
  id: 'action-002',
  verb: 'send',
  subject: {
    $id: 'agent:sdr-1',
    $type: 'SoftwareApplication',
    name: 'Sales Development Rep',
  },
  object: {
    $id: 'email:789',
    $type: 'EmailMessage',
    recipient: '[email protected]',
    subject: 'Welcome to Acme',
  },
  timestamp: '2024-10-27T10:05:00Z',
  status: 'completed',
}

System Processes Payment

const action: BusinessAction = {
  id: 'action-003',
  verb: 'process',
  subject: 'system:payment-processor',
  object: {
    $id: 'payment:999',
    $type: 'PaymentChargeSpecification',
    price: 199.98,
    priceCurrency: 'USD',
  },
  timestamp: '2024-10-27T10:10:00Z',
  status: 'in_progress',
  context: {
    processor: 'stripe',
    attempt: 1,
  },
}

BusinessEvent

An event represents something that happened in the system.

interface BusinessEvent {
  id: string
  type: string
  timestamp: string
  source: string
  data: Record<string, any>
  resources?: BusinessResource[]
  metadata?: Record<string, any>
}

Properties

id

  • Type: string
  • Required: Yes
  • Description: Unique identifier for the event.
id: 'evt-123'
id: 'user.created-456'
id: 'order.completed-789'

type

  • Type: string
  • Required: Yes
  • Description: The type of event that occurred. Use dot notation for namespacing.
type: 'user.created'
type: 'order.completed'
type: 'payment.succeeded'
type: 'workflow.completed'

timestamp

  • Type: string
  • Required: Yes
  • Description: When the event occurred (ISO 8601 format).
timestamp: '2024-10-27T10:00:00Z'

source

  • Type: string
  • Required: Yes
  • Description: Where the event originated from.
source: 'auth-service'
source: 'payment-processor'
source: 'workflow-engine'
source: 'user-api'

data

  • Type: Record<string, any>
  • Required: Yes
  • Description: Event-specific data payload.
data: {
  userId: '123',
  email: '[email protected]',
  emailVerified: true,
}

resources

  • Type: BusinessResource[]
  • Required: No
  • Description: Resources related to this event.
resources: [
  {
    $id: 'user:123',
    $type: 'Person',
    name: 'John Doe',
  },
]

metadata

  • Type: Record<string, any>
  • Required: No
  • Description: Additional metadata about the event.
metadata: {
  ipAddress: '192.168.1.1',
  userAgent: 'Mozilla/5.0...',
  traceId: 'trace-123',
}

Examples

User Created Event

const event: BusinessEvent = {
  id: 'evt-user-created-123',
  type: 'user.created',
  timestamp: '2024-10-27T10:00:00Z',
  source: 'auth-service',
  data: {
    userId: '123',
    email: '[email protected]',
    emailVerified: false,
    signupSource: 'landing-page',
  },
  resources: [
    {
      $id: 'user:123',
      $type: 'Person',
      name: 'John Doe',
      email: '[email protected]',
    },
  ],
  metadata: {
    ipAddress: '192.168.1.1',
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
  },
}

Order Completed Event

const event: BusinessEvent = {
  id: 'evt-order-completed-456',
  type: 'order.completed',
  timestamp: '2024-10-27T10:30:00Z',
  source: 'order-service',
  data: {
    orderId: '456',
    orderNumber: 'ORD-2024-001',
    totalAmount: 199.98,
    currency: 'USD',
    customerId: '123',
  },
  resources: [
    {
      $id: 'order:456',
      $type: 'Order',
      orderNumber: 'ORD-2024-001',
      orderStatus: 'Completed',
    },
    {
      $id: 'user:123',
      $type: 'Person',
      name: 'John Doe',
    },
  ],
}

Payment Succeeded Event

const event: BusinessEvent = {
  id: 'evt-payment-succeeded-789',
  type: 'payment.succeeded',
  timestamp: '2024-10-27T10:15:00Z',
  source: 'stripe',
  data: {
    paymentId: 'pi_123456789',
    amount: 19998, // cents
    currency: 'usd',
    status: 'succeeded',
    customerId: 'cus_123',
    metadata: {
      orderId: '456',
    },
  },
  resources: [
    {
      $id: 'payment:789',
      $type: 'PaymentChargeSpecification',
      price: 199.98,
      priceCurrency: 'USD',
    },
  ],
  metadata: {
    processor: 'stripe',
    attempt: 1,
  },
}

Workflow Completed Event

const event: BusinessEvent = {
  id: 'evt-workflow-completed-999',
  type: 'workflow.completed',
  timestamp: '2024-10-27T11:00:00Z',
  source: 'workflow-engine',
  data: {
    workflowId: 'user-onboarding',
    executionId: 'exec-123',
    duration: 45000, // ms
    steps: 5,
    status: 'completed',
  },
  resources: [
    {
      $id: 'workflow:user-onboarding',
      $type: 'SoftwareApplication',
      name: 'User Onboarding',
    },
  ],
  metadata: {
    triggeredBy: 'user.created',
    userId: '123',
  },
}

BusinessQuery

A query represents a search or filter operation.

interface BusinessQuery {
  id?: string
  query: string
  types?: string[]
  filters?: Record<string, any>
  sort?: {
    field: string
    order: 'asc' | 'desc'
  }
  pagination?: {
    page: number
    pageSize: number
  }
}

Properties

id

  • Type: string
  • Required: No
  • Description: Optional unique identifier for the query (useful for saved queries).
id: 'saved-query-123'
id: 'dashboard-query-active-users'

query

  • Type: string
  • Required: Yes
  • Description: The search query string.
query: 'software engineer'
query: 'orders status:completed'
query: 'high value customers'

types

  • Type: string[]
  • Required: No
  • Description: Resource types to search. Limits search to specific types.
types: ['Person']
types: ['Order', 'Invoice']
types: ['Organization']

filters

  • Type: Record<string, any>
  • Required: No
  • Description: Additional filters to apply.
filters: {
  status: 'active',
  createdAfter: '2024-01-01',
}

sort

  • Type: { field: string; order: 'asc' | 'desc' }
  • Required: No
  • Description: How to sort results.
sort: {
  field: 'createdAt',
  order: 'desc',
}

pagination

  • Type: { page: number; pageSize: number }
  • Required: No
  • Description: Pagination settings.
pagination: {
  page: 1,
  pageSize: 25,
}

Examples

const query: BusinessQuery = {
  query: 'software engineer',
  types: ['Person'],
}
const query: BusinessQuery = {
  query: 'customers',
  types: ['Person', 'Organization'],
  filters: {
    status: 'active',
    totalSpent: { $gt: 1000 },
    createdAt: { $gte: '2024-01-01' },
  },
  sort: {
    field: 'totalSpent',
    order: 'desc',
  },
  pagination: {
    page: 1,
    pageSize: 50,
  },
}
const query: BusinessQuery = {
  id: 'recent-orders',
  query: 'orders',
  types: ['Order'],
  filters: {
    status: 'completed',
    totalPrice: { $gt: 100 },
  },
  sort: {
    field: 'orderDate',
    order: 'desc',
  },
  pagination: {
    page: 1,
    pageSize: 10,
  },
}
const query: BusinessQuery = {
  query: 'acme',
  types: ['Organization', 'Product', 'Order'],
  filters: {
    $or: [{ name: { $contains: 'acme' } }, { description: { $contains: 'acme' } }],
  },
}

BusinessMetric

A metric represents a measurement or KPI.

interface BusinessMetric {
  id: string
  name: string
  type: 'kpi' | 'okr' | 'counter' | 'gauge' | 'histogram'
  value: number | string
  target?: number | string
  unit?: string
  timestamp?: string
  metadata?: Record<string, any>
}

Properties

id

  • Type: string
  • Required: Yes
  • Description: Unique identifier for the metric.
id: 'monthly-revenue'
id: 'active-users'
id: 'conversion-rate'

name

  • Type: string
  • Required: Yes
  • Description: Human-readable name for the metric.
name: 'Monthly Recurring Revenue'
name: 'Active Users'
name: 'Conversion Rate'

type

  • Type: 'kpi' | 'okr' | 'counter' | 'gauge' | 'histogram'
  • Required: Yes
  • Description: The type of metric.

Metric Types:

  • kpi: Key Performance Indicator (has target)
  • okr: Objective and Key Result (has target)
  • counter: Incrementing count
  • gauge: Point-in-time value
  • histogram: Distribution of values

value

  • Type: number | string
  • Required: Yes
  • Description: Current value of the metric.
value: 150000
value: 5000
value: '95.5%'

target

  • Type: number | string
  • Required: No (for KPIs and OKRs)
  • Description: Target value for the metric.
target: 200000
target: 10000
target: '98%'

unit

  • Type: string
  • Required: No
  • Description: Unit of measurement.
unit: 'USD'
unit: 'users'
unit: 'percent'
unit: 'ms'

timestamp

  • Type: string
  • Required: No
  • Description: When the metric was measured (ISO 8601 format).
timestamp: '2024-10-27T10:00:00Z'

metadata

  • Type: Record<string, any>
  • Required: No
  • Description: Additional metadata about the metric.
metadata: {
  period: 'monthly',
  department: 'sales',
  calculated: true,
}

Examples

KPI: Monthly Recurring Revenue

const metric: BusinessMetric = {
  id: 'mrr',
  name: 'Monthly Recurring Revenue',
  type: 'kpi',
  value: 150000,
  target: 200000,
  unit: 'USD',
  timestamp: '2024-10-27T00:00:00Z',
  metadata: {
    period: 'monthly',
    department: 'revenue',
    growthRate: 0.15, // 15% MoM growth
  },
}

Counter: Active Users

const metric: BusinessMetric = {
  id: 'active-users',
  name: 'Active Users',
  type: 'counter',
  value: 5000,
  unit: 'users',
  timestamp: '2024-10-27T10:00:00Z',
  metadata: {
    period: 'daily',
    definition: 'Users who logged in within last 24h',
  },
}

Gauge: Conversion Rate

const metric: BusinessMetric = {
  id: 'conversion-rate',
  name: 'Conversion Rate',
  type: 'gauge',
  value: '2.5%',
  target: '3.0%',
  unit: 'percent',
  timestamp: '2024-10-27T10:00:00Z',
  metadata: {
    period: 'weekly',
    funnel: 'signup-to-paid',
  },
}

OKR: Increase Revenue by 50%

const metric: BusinessMetric = {
  id: 'q4-revenue-okr',
  name: 'Q4 Revenue Growth',
  type: 'okr',
  value: 2200000,
  target: 3000000,
  unit: 'USD',
  timestamp: '2024-10-27T00:00:00Z',
  metadata: {
    objective: 'Increase Revenue by 50%',
    keyResult: 'Reach $3M ARR by end of Q4',
    progress: 0.73, // 73% complete
    owner: 'cfo',
  },
}

Histogram: Response Time

const metric: BusinessMetric = {
  id: 'api-response-time',
  name: 'API Response Time',
  type: 'histogram',
  value: {
    p50: 150,
    p95: 450,
    p99: 800,
  },
  unit: 'ms',
  timestamp: '2024-10-27T10:00:00Z',
  metadata: {
    endpoint: '/api/v1/orders',
    period: 'hourly',
  },
}

Type Relationships

Understanding how types relate to each other:

graph TB subgraph Execution["Execution Layer"] BF[BusinessFunction<br/>Atomic operations] WS[WorkflowStep<br/>Uses functions] BW[BusinessWorkflow<br/>Contains steps] WT[WorkflowTrigger<br/>Starts workflows] BA[BusinessAgent<br/>Executes functions & workflows] end subgraph Data["Data Layer"] BR[BusinessResource<br/>Entities] BAc[BusinessAction<br/>Operations on resources] BE[BusinessEvent<br/>Records actions] end subgraph Analytics["Analytics Layer"] BQ[BusinessQuery<br/>Finds resources] BM[BusinessMetric<br/>Measures performance] end BF --> WS WS --> BW WT --> BW BA --> BF BA --> BW BR --> BAc BAc --> BE BQ --> BR BE --> BM

Next Steps

See Also

On this page

BusinessFunctionPropertiesidnamedescriptioninputoutputexecutemetadataGeneric TypesExamplesSimple FunctionFunction with External APIFunction with DatabaseFunction with Error HandlingBusinessWorkflowPropertiesidnamedescriptionstepstriggersmetadataExamplesSimple WorkflowConditional WorkflowParallel WorkflowHuman-in-the-Loop WorkflowWorkflowStepPropertiesidnametypefunctionconditionnextconfigStep Types in DetailFunction StepCondition StepParallel StepLoop StepHuman StepAgent StepExamplesSequential StepsConditional BranchingError HandlingWorkflowTriggerPropertiestypeconfigconditionTrigger Types in DetailSchedule TriggerEvent TriggerWebhook TriggerManual TriggerExamplesMultiple TriggersConditional TriggerBusinessAgentPropertiesidnamedescriptionrolefunctionsworkflowscapabilitiesconfigExamplesSales Development RepMarketing Operations AgentSoftware Engineer AgentCustom AgentBusinessResourceProperties$id$typeAdditional PropertiesExamplesPerson ResourceOrganization ResourceProduct ResourceOrder ResourceBusinessActionPropertiesidverbsubjectobjecttimestampstatuscontextExamplesUser Creates OrderAgent Sends EmailSystem Processes PaymentBusinessEventPropertiesidtypetimestampsourcedataresourcesmetadataExamplesUser Created EventOrder Completed EventPayment Succeeded EventWorkflow Completed EventBusinessQueryPropertiesidquerytypesfilterssortpaginationExamplesSimple SearchFiltered SearchOrder SearchMulti-Type SearchBusinessMetricPropertiesidnametypevaluetargetunittimestampmetadataExamplesKPI: Monthly Recurring RevenueCounter: Active UsersGauge: Conversion RateOKR: Increase Revenue by 50%Histogram: Response TimeType RelationshipsNext StepsSee Also