Primitives.org.ai

Task

Task management primitives for digital workers - combining functions with status, dependencies, and workflow orchestration

Wrap Functions with lifecycle management, making them executable units of work with status tracking, dependencies, and worker assignment. Every task is a Function + metadata.

What is a Task?

A Task extends a Function (Code, Generative, Agentic, or Human) with:

  • Status tracking: pending, queued, assigned, in_progress, blocked, completed, failed
  • Priority levels: low, normal, high, urgent, critical
  • Worker assignment: Who or what should complete it (agent, human, team)
  • Dependencies: Tasks that must complete first
  • Progress tracking: Percent complete, current step, estimated time
import { createTask } from 'digital-tasks'
import type { FunctionDefinition } from 'ai-functions'

// Define the function this task executes
const summarizeFunction: FunctionDefinition = {
  type: 'generative',
  name: 'summarize',
  description: 'Summarize a document',
  args: { text: 'The text to summarize' },
  output: 'string',
  promptTemplate: 'Summarize: {{text}}',
}

// Create a task from the function
const task = await createTask({
  function: summarizeFunction,
  input: { text: 'Long article content...' },
  priority: 'high',
})

console.log(task.id)      // task_1234567890_abc123
console.log(task.status)  // 'queued'

Task = Function + Metadata

AspectFunctionTask
FocusHow to do somethingWhat needs to be done
DurationUsually quickCan span hours or days
AssignmentImplicitExplicit (human, agent, team)
TrackingExecution onlyFull lifecycle
DependenciesNoneSupports blocking dependencies

Function Types

Tasks wrap one of four function types:

// Code function - deterministic execution
const codeTask = await createTask({
  function: {
    type: 'code',
    name: 'processData',
    args: { data: 'Input data' },
    output: 'object',
    code: 'return transform(data)',
    language: 'typescript',
  },
})

// Generative function - AI generates content
const generativeTask = await createTask({
  function: {
    type: 'generative',
    name: 'writeEmail',
    args: { topic: 'Meeting follow-up' },
    output: 'string',
    promptTemplate: 'Write an email about: {{topic}}',
  },
})

// Agentic function - AI with tools in a loop
const agenticTask = await createTask({
  function: {
    type: 'agentic',
    name: 'research',
    args: { query: 'Research topic' },
    output: 'object',
    tools: ['web_search', 'read_file'],
  },
})

// Human function - requires human input
const humanTask = await createTask({
  function: {
    type: 'human',
    name: 'approve',
    description: 'Manager approval required',
    args: { request: 'Approval request' },
    output: 'object',
    instructions: 'Please review and approve or reject',
  },
})

Task Lifecycle

import {
  createTask,
  startTask,
  updateProgress,
  completeTask,
  failTask,
  cancelTask,
} from 'digital-tasks'

// 1. Create task
const task = await createTask({ function: myFunction })

// 2. Start work
await startTask(task.id, { type: 'agent', id: 'agent_1', name: 'Worker' })

// 3. Update progress
await updateProgress(task.id, 50, 'Processing data')
await updateProgress(task.id, 75, 'Generating output')

// 4. Complete or fail
await completeTask(task.id, 'Task result')
// or
await failTask(task.id, 'Error message')
// or
await cancelTask(task.id, 'No longer needed')

Status Flow

┌──────────┐    ┌──────────┐    ┌─────────────┐    ┌───────────┐
│  pending │ -> │  queued  │ -> │ in_progress │ -> │ completed │
└──────────┘    └──────────┘    └─────────────┘    └───────────┘
     │               │                 │                  │
     v               v                 v                  v
┌──────────┐    ┌─────────┐      ┌──────────┐      ┌──────────┐
│ scheduled│    │ blocked │      │  failed  │      │ cancelled│
└──────────┘    └─────────┘      └──────────┘      └──────────┘

Project DSL

Define task workflows using the declarative DSL:

import { task, parallel, sequential, createProject, workflow } from 'digital-tasks'

// Create individual tasks
const design = task('Design mockups', { priority: 'high' })
const spec = task('Write technical spec')
const backend = task('Implement backend', { functionType: 'code' })
const frontend = task('Implement frontend')
const tests = task('Write tests')
const review = task('Code review', { functionType: 'human' })

// Organize into parallel and sequential groups
const project = createProject({
  name: 'Launch Feature',
  tasks: [
    // These run in parallel
    parallel(design, spec),
    // These run sequentially
    sequential(backend, frontend, tests),
    // Final review
    review,
  ],
})

// Or use the fluent builder
const project2 = workflow('Launch Feature')
  .parallel(
    task('Design'),
    task('Spec'),
  )
  .then(task('Implement'))
  .then(task('Test'))
  .build()

Dependencies

Tasks can depend on other tasks:

const task1 = await createTask({ function: func1 })
const task2 = await createTask({
  function: func2,
  dependencies: [task1.id],  // task2 blocked until task1 completes
})

console.log(task2.status)  // 'blocked'

// When task1 completes, task2 automatically unblocks
await completeTask(task1.id, 'done')
const updated = await getTask(task2.id)
console.log(updated.status)  // 'queued'

Dependency Graph Utilities

import {
  getDependants,
  getDependencies,
  getReadyTasks,
  hasCycles,
  sortTasks,
} from 'digital-tasks'

// Get tasks that depend on this one
const dependants = getDependants(task.id, allTasks)

// Get tasks this one depends on
const deps = getDependencies(task, allTasks)

// Get tasks ready to execute (no unsatisfied deps)
const ready = getReadyTasks(allTasks)

// Check for circular dependencies
const cyclic = hasCycles(allTasks)

// Get topologically sorted task order
const sorted = sortTasks(allTasks)

Task Queue

Manage task flow with priority-based queuing:

import { createTaskQueue, taskQueue } from 'digital-tasks'

// Use global queue
await taskQueue.add(task)
const next = await taskQueue.getNextForWorker({ type: 'agent', id: 'agent_1' })

// Or create isolated queue
const myQueue = createTaskQueue({ name: 'my-queue' })

// Query tasks
const urgentTasks = await myQueue.query({
  status: ['queued', 'in_progress'],
  priority: ['urgent', 'critical'],
  sortBy: 'priority',
  sortOrder: 'desc',
})

// Get queue stats
const stats = await myQueue.stats()
// { total: 100, byStatus: { queued: 50, ... }, byPriority: { high: 20, ... } }

Markdown Integration

Bidirectional conversion between tasks and markdown checklists:

import { parseMarkdown, toMarkdown } from 'digital-tasks'

// Parse markdown to project
const project = parseMarkdown(`
# Launch Feature

## Planning
- [ ] Design mockups
- [ ] Write technical spec
- [x] Create project board

## Implementation (sequential)
1. [ ] Implement backend API
2. [-] Implement frontend UI
   - [ ] Create components
   - [ ] Add state management
3. [ ] Write tests

## Deployment
1. [ ] Deploy to staging
2. [ ] QA testing
3. [ ] Deploy to production
`)

// Convert project back to markdown
const md = toMarkdown(project)

Markdown Syntax

SyntaxMeaning
- [ ]Parallel/unordered task (pending)
1. [ ]Sequential/ordered task (pending)
[x]Completed
[-]In progress
[~]Blocked
[!]Failed
!!Critical priority
!Urgent priority
^High priority
vLow priority

Worker Assignment

Tasks specify who can work on them:

// Explicit assignment
const task = await createTask({
  function: func,
  assignTo: { type: 'human', id: 'user_123', name: 'John' },
})

// Worker type constraints
const task2 = await createTask({
  function: humanFunc,  // type: 'human' -> allowedWorkers: ['human']
})

// Claim task
await taskQueue.claim(task.id, { type: 'agent', id: 'agent_1' })

Waiting for Completion

import { waitForTask } from 'digital-tasks'

// Wait for task to complete (with timeout)
const result = await waitForTask(task.id, {
  timeout: 5 * 60 * 1000,  // 5 minutes
  pollInterval: 1000,       // Check every second
})

if (result.success) {
  console.log('Output:', result.output)
  console.log('Duration:', result.metadata.duration)
} else {
  console.log('Error:', result.error.message)
}

Subtasks

Create hierarchical task structures:

import { createSubtask, getSubtasks } from 'digital-tasks'

const parent = await createTask({ function: parentFunc })

const sub1 = await createSubtask(parent.id, { function: subFunc1 })
const sub2 = await createSubtask(parent.id, { function: subFunc2 })

const subtasks = await getSubtasks(parent.id)
// [sub1, sub2]

Event History

Tasks track their full lifecycle:

const task = await createTask({ function: func })
await startTask(task.id, worker)
await addComment(task.id, 'Starting work', worker)
await updateProgress(task.id, 50, 'Halfway done')
await completeTask(task.id, 'result')

const updated = await getTask(task.id)
console.log(updated.events)
// [
//   { type: 'created', timestamp: ..., message: 'Task created: func' },
//   { type: 'assigned', timestamp: ..., actor: worker },
//   { type: 'started', timestamp: ..., actor: worker },
//   { type: 'comment', timestamp: ..., message: 'Starting work' },
//   { type: 'progress', timestamp: ..., data: { percent: 50 } },
//   { type: 'completed', timestamp: ... },
// ]

Types

import type {
  Task,
  TaskStatus,
  TaskPriority,
  WorkerRef,
  WorkerType,
  TaskDependency,
  TaskProgress,
  TaskEvent,
  TaskResult,
  TaskQueue,
  FunctionDefinition,
} from 'digital-tasks'

// Task status
type TaskStatus =
  | 'pending'
  | 'queued'
  | 'assigned'
  | 'in_progress'
  | 'blocked'
  | 'review'
  | 'completed'
  | 'failed'
  | 'cancelled'

// Task priority
type TaskPriority = 'low' | 'normal' | 'high' | 'urgent' | 'critical'

// Worker types
type WorkerType = 'agent' | 'human' | 'team' | 'any'
Was this page helpful?

On this page