ServiceExecution API Reference
Complete API reference for the ServiceExecution type, including execution tracking, monitoring, and error handling
The $.ServiceExecution type tracks the actual execution of a service order. It provides real-time monitoring of progress, captures results, logs events, handles errors, and measures performance metrics throughout the execution lifecycle.
Type Definition
// @errors: 7006
interface ServiceExecution extends Thing {
$type: 'ServiceExecution'
$id: string
order: ServiceOrder
service: Service
status: ExecutionStatus
// ^^^^^^^^^^^^^^^^^
progress: number
//^^^^^^^^^^
assignee?: ExecutionAssignee
// ^^^^^^^^^^^^^^^^^
result?: ExecutionResult
logs?: ExecutionLog[]
metrics?: ExecutionMetrics
// ^^^^^^^^^^^^^^^^
error?: ExecutionError
steps?: ExecutionStep[]
checkpoints?: ExecutionCheckpoint[]
priority?: ExecutionPriority
timeout?: number
retryPolicy?: RetryPolicy
webhooks?: Webhook[]
tags?: string[]
metadata?: ExecutionMetadata
}
type ExecutionStatus =
| 'queued'
// ^^^^^^^^
| 'starting'
| 'running'
| 'paused'
| 'completed'
| 'failed'
| 'cancelled'
| 'retry'
type ExecutionPriority = 'low' | 'normal' | 'high' | 'urgent'
interface ExecutionAssignee {
type: 'ai-agent' | 'human' | 'hybrid' | 'system'
// ^^^^^^^^^^
id: string
name: string
model?: string
}
interface ExecutionResult {
success: boolean
//^^^^^^^
output: any
summary: string
artifacts?: string[]
}
interface ExecutionLog {
timestamp: string
level: 'debug' | 'info' | 'warn' | 'error'
// ^^^^^^^
message: string
context?: Record<string, any>
step?: string
}
interface ExecutionMetrics {
startedAt?: string
completedAt?: string
duration?: number
//^^^^^^^^
tokensUsed?: number
cost?: number
apiCalls?: number
retries?: number
stepsCompleted: number
stepsTotal: number
}
interface ExecutionError {
code: string
message: string
stack?: string
step?: string
recoverable: boolean
//^^^^^^^^^^^
retryCount: number
}
interface ExecutionStep {
id: string
name: string
status: StepStatus
startedAt?: string
completedAt?: string
duration?: number
assignee?: ExecutionAssignee
input?: any
output?: any
error?: ExecutionError
}
type StepStatus = 'pending' | 'running' | 'completed' | 'failed' | 'skipped'
interface ExecutionCheckpoint {
id: string
timestamp: string
state: Record<string, any>
step: string
}
interface RetryPolicy {
maxRetries: number
backoff: 'linear' | 'exponential'
initialDelay: number
maxDelay: number
}
interface Webhook {
url: string
events: string[]
headers?: Record<string, string>
}
interface ExecutionMetadata {
createdAt: string
updatedAt: string
startedAt?: string
completedAt?: string
environment?: string
version?: string
}Properties
Core Properties
order
- Type:
ServiceOrder - Required: Yes
- Description: The order being executed
- Pattern:
$.ServiceExecution[id].order -> $.ServiceOrder[orderId]
service
- Type:
Service - Required: Yes
- Description: The service being executed
- Pattern:
$.ServiceExecution[id].service -> $.Service[serviceId]
status
- Type:
ExecutionStatus - Required: Yes
- Default:
'queued' - Values:
'queued' | 'starting' | 'running' | 'paused' | 'completed' | 'failed' | 'cancelled' | 'retry' - Description: Current execution status
progress
- Type:
number - Required: No
- Default:
0 - Range:
0-100 - Description: Execution progress percentage
Execution Properties
assignee
- Type:
ExecutionAssignee - Required: No
- Description: Who/what is executing the service
- Properties:
type: Execution type (ai-agent, human, hybrid, system)id: Assignee identifiername: Assignee namemodel: AI model (for AI agents)
result
- Type:
ExecutionResult - Required: No
- Description: Execution result and outputs
- Set: When execution completes
- Properties:
success: Whether execution succeededoutput: Execution output datasummary: Human-readable summaryartifacts: URLs to generated files
steps
- Type:
ExecutionStep[] - Required: No
- Description: Individual workflow steps
- Tracked: Each step's status, duration, and results
Monitoring Properties
logs
- Type:
ExecutionLog[] - Required: No
- Description: Execution event logs
- Levels: debug, info, warn, error
- Retention: 30 days
metrics
- Type:
ExecutionMetrics - Required: No
- Description: Performance metrics
- Tracked:
- Start/completion times
- Duration
- Tokens used (AI)
- Cost
- API calls
- Retries
- Steps completed/total
error
- Type:
ExecutionError - Required: No
- Description: Error information (if failed)
- Properties:
code: Error codemessage: Error messagestack: Stack tracestep: Step where error occurredrecoverable: Whether retry is possibleretryCount: Number of retry attempts
Advanced Properties
checkpoints
- Type:
ExecutionCheckpoint[] - Required: No
- Description: Execution checkpoints for resumption
- Created: Automatically every 15 minutes
- Used: For pausing/resuming long-running executions
priority
- Type:
ExecutionPriority - Required: No
- Default:
'normal' - Values:
'low' | 'normal' | 'high' | 'urgent'
timeout
- Type:
number - Required: No
- Default:
3600000(1 hour) - Description: Execution timeout in milliseconds
retryPolicy
- Type:
RetryPolicy - Required: No
- Description: Retry configuration for failures
webhooks
- Type:
Webhook[] - Required: No
- Description: Webhook callbacks for execution events
Methods
create()
Create a new execution (usually automatic on order confirm).
Signature:
$.ServiceExecution.create(config: ExecutionConfig): Promise<ServiceExecution>Parameters:
config: Execution configuration object
Returns: Promise resolving to the created ServiceExecution
Example:
const execution = await $.ServiceExecution.create({
order: $.ServiceOrder.get(orderId),
service: $.Service.get(serviceId),
status: 'queued',
progress: 0,
assignee: {
type: 'ai-agent',
id: 'claude-agent-1',
name: 'Claude SDR Agent',
model: 'claude-sonnet-4.5',
},
priority: 'normal',
timeout: 3600000,
retryPolicy: {
maxRetries: 3,
backoff: 'exponential',
initialDelay: 1000,
maxDelay: 60000,
},
})get()
Retrieve an execution by ID.
Signature:
$.ServiceExecution.get(id: string): Promise<ServiceExecution>Parameters:
id: Execution identifier
Returns: Promise resolving to the ServiceExecution
Example:
const execution = await $.ServiceExecution.get('execution-123')
console.log(execution.status)
console.log(execution.progress)list()
List all executions with optional filtering.
Signature:
$.ServiceExecution.list(filter?: ExecutionFilter): Promise<ServiceExecution[]>Parameters:
filter: Optional filter criteria
Returns: Promise resolving to array of ServiceExecutions
Example:
// List all executions
const allExecutions = await $.ServiceExecution.list()
// List running executions
const runningExecutions = await $.ServiceExecution.list({
status: 'running',
})find()
Find executions matching specific criteria.
Signature:
$.ServiceExecution.find(query: ExecutionQuery): Promise<ServiceExecution[]>Parameters:
query: Query object with filter criteria
Returns: Promise resolving to matching ServiceExecutions
Example:
// Find by status
const failedExecutions = await $.ServiceExecution.find({
status: 'failed',
})
// Find by service
const serviceExecutions = await $.ServiceExecution.find({
service: 'service-id',
})
// Find by date range
const recentExecutions = await $.ServiceExecution.find({
'metadata.createdAt': {
$gte: startDate,
$lte: endDate,
},
})start()
Start execution.
Signature:
$.ServiceExecution[id].start(): Promise<ServiceExecution>Returns: Promise resolving to started ServiceExecution
Side Effects: Updates status to 'running', sets startedAt
Example:
await $.ServiceExecution[executionId].start()
// Status: 'queued' -> 'running'pause()
Pause execution.
Signature:
$.ServiceExecution[id].pause(): Promise<ServiceExecution>Returns: Promise resolving to paused ServiceExecution
Side Effects: Creates checkpoint, updates status to 'paused'
Example:
await $.ServiceExecution[executionId].pause()
// Status: 'running' -> 'paused'resume()
Resume paused execution.
Signature:
$.ServiceExecution[id].resume(): Promise<ServiceExecution>Returns: Promise resolving to resumed ServiceExecution
Side Effects: Restores from checkpoint, updates status to 'running'
Example:
await $.ServiceExecution[executionId].resume()
// Status: 'paused' -> 'running'cancel()
Cancel execution.
Signature:
$.ServiceExecution[id].cancel(reason?: string): Promise<ServiceExecution>Parameters:
reason: Optional cancellation reason
Returns: Promise resolving to cancelled ServiceExecution
Example:
await $.ServiceExecution[executionId].cancel('User requested cancellation')complete()
Mark execution as completed.
Signature:
$.ServiceExecution[id].complete(result: ExecutionResult): Promise<ServiceExecution>Parameters:
result: Execution result object
Returns: Promise resolving to completed ServiceExecution
Example:
await $.ServiceExecution[executionId].complete({
success: true,
output: {
emails_sent: 2,
responses_received: 0,
bounce_rate: 0,
},
summary: 'Successfully sent outreach to 2 leads',
artifacts: ['https://files.services.do/reports/exec-123.pdf'],
})fail()
Mark execution as failed.
Signature:
$.ServiceExecution[id].fail(error: ExecutionError): Promise<ServiceExecution>Parameters:
error: Error object
Returns: Promise resolving to failed ServiceExecution
Example:
await $.ServiceExecution[executionId].fail({
code: 'EMAIL_SERVICE_ERROR',
message: 'Failed to send email via SMTP',
recoverable: true,
retryCount: 0,
})updateProgress()
Update execution progress.
Signature:
$.ServiceExecution[id].updateProgress(progress: number): Promise<ServiceExecution>Parameters:
progress: Progress percentage (0-100)
Returns: Promise resolving to updated ServiceExecution
Example:
await $.ServiceExecution[executionId].updateProgress(45)
// progress: 0 -> 45log()
Add a log entry.
Signature:
$.ServiceExecution[id].log(log: ExecutionLog): Promise<void>Parameters:
log: Log entry object
Returns: Promise resolving when complete
Example:
await $.ServiceExecution[executionId].log({
level: 'info',
message: 'Starting lead research',
step: 'research-lead',
})
await $.ServiceExecution[executionId].log({
level: 'error',
message: 'API rate limit exceeded',
context: {
api: 'linkedin',
limit: 100,
period: '1h',
},
})watch()
Watch execution progress in real-time.
Signature:
$.ServiceExecution[id].watch(): ExecutionWatcherReturns: ExecutionWatcher instance
Example:
const watcher = $.ServiceExecution[executionId].watch()
watcher.on('progress', (progress) => {
console.log(`Progress: ${progress}%`)
})
watcher.on('status_changed', (status) => {
console.log(`Status: ${status}`)
})
watcher.on('completed', (result) => {
console.log('Execution completed:', result)
watcher.stop()
})
watcher.on('failed', (error) => {
console.error('Execution failed:', error)
watcher.stop()
})Property Access
ServiceExecutions support semantic property access:
// Get execution status
const status = await $.ServiceExecution[executionId].status
// Get progress
const progress = await $.ServiceExecution[executionId].progress
// Get result
const result = await $.ServiceExecution[executionId].result
// Get metrics
const metrics = await $.ServiceExecution[executionId].metrics
// Get logs
const logs = await $.ServiceExecution[executionId].logs
// Get steps
const steps = await $.ServiceExecution[executionId].stepsRelations
order
Access the order being executed.
Pattern: $.ServiceExecution[id].order -> $.ServiceOrder[orderId]
Example:
const execution = await $.ServiceExecution.get('execution-123')
const order = await execution.order
console.log(order.customer)service
Access the service being executed.
Pattern: $.ServiceExecution[id].service -> $.Service[serviceId]
Example:
const service = await $.ServiceExecution[executionId].service
console.log(service.name)workflow
Access the workflow (from service).
Pattern: $.ServiceExecution[id].workflow -> $.BusinessWorkflow[workflowId]
Example:
const workflow = await $.ServiceExecution[executionId].workflow
console.log(`Steps: ${workflow.steps.length}`)customer
Access the customer (from order).
Pattern: $.ServiceExecution[id].customer -> $.User[customerId]
Example:
const customer = await $.ServiceExecution[executionId].customer
console.log(customer.name)Usage Examples
Example 1: AI SDR Outreach Execution
const execution = await $.ServiceExecution.create({
order: $.ServiceOrder.get('order-123'),
service: $.Service.get('sdr-service'),
status: 'queued',
assignee: {
type: 'ai-agent',
id: 'claude-sdr-1',
name: 'Claude SDR Agent',
model: 'claude-sonnet-4.5',
},
steps: [
{
id: 'research-lead-1',
name: 'Research John Doe',
status: 'pending',
assignee: { type: 'ai-agent', model: 'claude-sonnet-4.5' },
},
{
id: 'craft-message-1',
name: 'Craft Message for John Doe',
status: 'pending',
assignee: { type: 'ai-agent', model: 'claude-sonnet-4.5' },
},
{
id: 'send-email-1',
name: 'Send Email to John Doe',
status: 'pending',
assignee: { type: 'system' },
},
],
metrics: {
stepsTotal: 3,
stepsCompleted: 0,
},
})
// Execution progresses automatically
// Final result:
// {
// status: 'completed',
// progress: 100,
// result: {
// success: true,
// output: {
// emails_sent: 1,
// leads_contacted: 1,
// bounce_rate: 0,
// personalization_quality: 0.92
// },
// summary: 'Successfully sent personalized outreach to 1 lead'
// }
// }Example 2: Monitor Execution Progress
const execution = await $.ServiceExecution.get('execution-id')
// Watch execution
const watcher = execution.watch()
watcher.on('progress', (progress) => {
console.log(`Progress: ${progress}%`)
})
watcher.on('step.started', (step) => {
console.log(`Started: ${step.name}`)
})
watcher.on('step.completed', (step) => {
console.log(`Completed: ${step.name} (${step.duration}ms)`)
})
watcher.on('completed', (result) => {
console.log('Execution completed successfully!')
console.log(result.summary)
watcher.stop()
})
watcher.on('failed', (error) => {
console.error('Execution failed:', error.message)
watcher.stop()
})Example 3: Hybrid Human-AI Execution
const execution = await $.ServiceExecution.create({
order: $.ServiceOrder.get('order-456'),
service: $.Service.get('content-service'),
status: 'queued',
assignee: {
type: 'hybrid',
id: 'content-team',
name: 'Content Team (AI + Human)',
},
steps: [
{
id: 'research',
name: 'Research Topic',
status: 'pending',
assignee: { type: 'ai-agent', model: 'claude-sonnet-4.5' },
},
{
id: 'outline',
name: 'Create Outline',
status: 'pending',
assignee: { type: 'ai-agent', model: 'claude-sonnet-4.5' },
},
{
id: 'draft',
name: 'Write Draft',
status: 'pending',
assignee: { type: 'ai-agent', model: 'claude-sonnet-4.5' },
},
{
id: 'review',
name: 'Human Review',
status: 'pending',
assignee: { type: 'human', id: 'editor-1', name: 'Sarah Editor' },
},
{
id: 'publish',
name: 'Publish Content',
status: 'pending',
assignee: { type: 'system' },
},
],
})Example 4: Failed Execution with Retry
const execution = await $.ServiceExecution.create({
order: $.ServiceOrder.get('order-789'),
service: $.Service.get('integration-service'),
status: 'running',
retryPolicy: {
maxRetries: 3,
backoff: 'exponential',
initialDelay: 1000,
maxDelay: 60000,
},
})
// Simulate failure
await $.ServiceExecution[execution.$id].fail({
code: 'API_TIMEOUT',
message: 'External API timeout after 30s',
step: 'fetch-data',
recoverable: true,
retryCount: 0,
})
// System automatically retries with exponential backoff
// Logs show:
// - Error: API timeout after 30s
// - Warn: Retrying after 1s (attempt 1/3)
// - Error: API timeout after 30s
// - Warn: Retrying after 2s (attempt 2/3)
// - Success: Request completedExample 5: Long-Running Batch Execution
const execution = await $.ServiceExecution.create({
order: $.ServiceOrder.get('order-999'),
service: $.Service.get('batch-processing-service'),
status: 'running',
progress: 0,
assignee: {
type: 'system',
id: 'batch-processor',
name: 'Batch Processing System',
},
timeout: 7200000, // 2 hours
metrics: {
stepsTotal: 1000,
stepsCompleted: 0,
},
})
// Automatic checkpointing every 15 minutes
// If execution is interrupted, it can resume from last checkpointExample 6: Get Execution Logs
const execution = await $.ServiceExecution.get('execution-id')
// Get all logs
const allLogs = execution.logs
// Filter error logs
const errorLogs = allLogs.filter((log) => log.level === 'error')
console.log('Error Logs:')
errorLogs.forEach((log) => {
console.log(`[${log.timestamp}] ${log.message}`)
if (log.context) {
console.log('Context:', log.context)
}
})Example 7: Query Executions
// Get all running executions
const runningExecutions = await $.ServiceExecution.find({
status: 'running',
})
// Get executions by service
const serviceExecutions = await $.ServiceExecution.find({
service: 'service-id',
})
// Get failed executions for analysis
const failedExecutions = await $.ServiceExecution.find({
status: 'failed',
'metadata.createdAt': {
$gte: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
},
})
// Analyze failure patterns
const errorCodes = failedExecutions.reduce(
(acc, exec) => {
const code = exec.error?.code || 'UNKNOWN'
acc[code] = (acc[code] || 0) + 1
return acc
},
{} as Record<string, number>
)
console.log('Error Distribution:', errorCodes)Example 8: Pause and Resume Execution
// Pause execution
await $.ServiceExecution[executionId].pause()
console.log('Execution paused')
// Do something else...
await someOtherOperation()
// Resume execution
await $.ServiceExecution[executionId].resume()
console.log('Execution resumed')Example 9: Track Step Progress
// Start execution
await $.ServiceExecution[executionId].start()
// Track each step
for (const step of workflow.steps) {
// Start step
await $.ServiceExecution[executionId].startStep({
id: step.id,
name: step.name,
assignee: step.assignee,
})
// Execute step logic
const stepResult = await executeStep(step)
// Complete step
await $.ServiceExecution[executionId].completeStep(step.id, {
output: stepResult,
})
// Update overall progress
const progress = (completedSteps / totalSteps) * 100
await $.ServiceExecution[executionId].updateProgress(progress)
}
// Complete execution
await $.ServiceExecution[executionId].complete({
success: true,
output: finalResult,
summary: 'All steps completed successfully',
})Example 10: Get Execution Metrics
const execution = await $.ServiceExecution.get('execution-id')
console.log('Execution Metrics:')
console.log(`- Duration: ${execution.metrics.duration}ms`)
console.log(`- Tokens Used: ${execution.metrics.tokensUsed}`)
console.log(`- Cost: $${execution.metrics.cost}`)
console.log(`- API Calls: ${execution.metrics.apiCalls}`)
console.log(`- Retries: ${execution.metrics.retries}`)
console.log(`- Steps: ${execution.metrics.stepsCompleted}/${execution.metrics.stepsTotal}`)
// Calculate efficiency
const avgStepDuration = execution.metrics.duration / execution.metrics.stepsCompleted
console.log(`- Avg Step Duration: ${avgStepDuration.toFixed(0)}ms`)Example 11: Configure Webhooks
const execution = await $.ServiceExecution.create({
order: $.ServiceOrder.get('order-id'),
service: $.Service.get('service-id'),
status: 'queued',
webhooks: [
{
url: 'https://api.example.com/webhooks/execution',
events: ['status_changed', 'completed', 'failed'],
headers: {
Authorization: 'Bearer token123',
'X-Webhook-Secret': 'secret456',
},
},
{
url: 'https://slack.com/api/webhooks/abc123',
events: ['completed', 'failed'],
},
],
})Example 12: Batch Execution Analytics
// Get all executions for a service
const service = await $.Service.get('service-id')
const executions = await $.ServiceExecution.find({
service: service.$id,
})
// Calculate analytics
const stats = {
total: executions.length,
completed: executions.filter((e) => e.status === 'completed').length,
failed: executions.filter((e) => e.status === 'failed').length,
avgDuration: executions.filter((e) => e.metrics?.duration).reduce((sum, e) => sum + e.metrics.duration, 0) / executions.length,
totalCost: executions.reduce((sum, e) => sum + (e.metrics?.cost || 0), 0),
successRate: executions.filter((e) => e.status === 'completed').length / executions.length,
}
console.log('Service Execution Analytics:')
console.log(`- Total Executions: ${stats.total}`)
console.log(`- Success Rate: ${(stats.successRate * 100).toFixed(1)}%`)
console.log(`- Average Duration: ${(stats.avgDuration / 1000).toFixed(1)}s`)
console.log(`- Total Cost: $${stats.totalCost.toFixed(2)}`)Execution Status Lifecycle
Executions progress through these statuses:
- queued: Waiting to start
- starting: Initializing execution
- running: Currently executing
- paused: Temporarily paused (can be resumed)
- completed: Successfully completed
- failed: Execution failed
- cancelled: Execution cancelled
- retry: Retrying after failure
Status Transitions:
// queued -> starting -> running
await execution.start()
// running -> paused
await execution.pause()
// paused -> running
await execution.resume()
// running -> completed
await execution.complete(result)
// running -> failed
await execution.fail(error)
// any -> cancelled
await execution.cancel()Events
ServiceExecutions emit the following events:
execution.created- Execution was createdexecution.started- Execution startedexecution.progress- Progress updatedexecution.paused- Execution pausedexecution.resumed- Execution resumedexecution.completed- Execution completedexecution.failed- Execution failedexecution.cancelled- Execution cancelledexecution.retry- Execution retryingexecution.step.started- Step startedexecution.step.completed- Step completedexecution.step.failed- Step failed
Example:
import { on } from 'sdk.do'
on.ServiceExecution.started(async (execution) => {
console.log(`Execution started: ${execution.$id}`)
})
on.ServiceExecution.completed(async (execution) => {
console.log(`Execution completed: ${execution.$id}`)
console.log(`Duration: ${execution.metrics.duration}ms`)
})
on.ServiceExecution.failed(async (execution) => {
console.error(`Execution failed: ${execution.error.message}`)
})API Endpoints
ServiceExecutions are accessible via REST API:
GET /api/executions- List executionsGET /api/executions/:id- Get execution detailsPOST /api/executions- Create executionPUT /api/executions/:id- Update executionPOST /api/executions/:id/start- Start executionPOST /api/executions/:id/pause- Pause executionPOST /api/executions/:id/resume- Resume executionPOST /api/executions/:id/cancel- Cancel executionPOST /api/executions/:id/complete- Complete executionPOST /api/executions/:id/fail- Fail executionGET /api/executions/:id/logs- Get logsPOST /api/executions/:id/logs- Add logGET /api/executions/:id/metrics- Get metricsWS /api/executions/:id/watch- Watch execution (WebSocket)
Real-time Monitoring
Executions support real-time monitoring via:
- WebSocket: Live status and progress updates
- Server-Sent Events (SSE): One-way streaming updates
- Webhooks: HTTP callbacks for events
- Polling: REST API polling (fallback)
WebSocket Example:
const ws = new WebSocket(`wss://api.services.do/executions/${executionId}/watch`)
ws.onmessage = (event) => {
const data = JSON.parse(event.data)
switch (data.type) {
case 'progress':
console.log(`Progress: ${data.progress}%`)
break
case 'status_changed':
console.log(`Status: ${data.status}`)
break
case 'completed':
console.log('Execution completed!')
ws.close()
break
}
}Performance Considerations
- Timeout: Default 1 hour, configurable up to 24 hours
- Checkpointing: Automatic checkpoints every 15 minutes for long executions
- Log Retention: Logs retained for 30 days, then archived
- Metrics Granularity: Step-level timing and cost tracking
- Retry Strategy: Exponential backoff with jitter (recommended)
Security
- Access Control: Only customer and provider can view execution
- Sensitive Data: Input/output may contain sensitive data, access restricted
- Audit Trail: All status changes and access logged
- Encryption: Results and logs encrypted at rest
Schema.org Mapping
ServiceExecutions extend Schema.org types:
- schema.org/Action: An action performed by an agent
Property Mappings:
actionStatus->statusagent->assigneeresult->resultstartTime->metrics.startedAtendTime->metrics.completedAterror->error
See Also
- Service API - Service definition
- ServiceOrder API - Service orders
- ServiceOffering API - Marketplace listings
- Execution Types - Type definitions