Tool for managing CRON-scheduled background jobs.
  • TypeScript 100%
Find a file
James Peret 64d94e7521 Refactor background-jobs-tool input validation and schema
- Consolidate discriminated union into single object schema
- Add centralized input validation with detailed error messages
- Improve TypeScript type safety and optional field handling
- Maintain backward compatibility with legacy type exports
- Enhance error handling and user feedback

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-10 14:36:25 -03:00
src Refactor background-jobs-tool input validation and schema 2025-09-10 14:36:25 -03:00
tests feat: implement comprehensive background jobs tool 2025-09-10 02:43:08 -03:00
.gitignore feat: implement comprehensive background jobs tool 2025-09-10 02:43:08 -03:00
package-lock.json feat: implement comprehensive background jobs tool 2025-09-10 02:43:08 -03:00
package.json feat: implement comprehensive background jobs tool 2025-09-10 02:43:08 -03:00
README.md feat: implement comprehensive background jobs tool 2025-09-10 02:43:08 -03:00
tsconfig.json feat: implement comprehensive background jobs tool 2025-09-10 02:43:08 -03:00
vitest.config.ts feat: implement comprehensive background jobs tool 2025-09-10 02:43:08 -03:00

Background Jobs Tool

A comprehensive AI tool for managing CRON-scheduled background jobs with autonomous AI agent execution in the Fractal Synapse project.

Overview

This tool provides a unified interface for creating, managing, and monitoring background jobs that are executed by AI agents on scheduled intervals. It integrates with the Background Jobs Plugin to provide full lifecycle management of scheduled tasks.

Features

  • Job Creation: Create new background jobs with CRON scheduling
  • Job Management: Update job properties, prompts, and scheduling
  • Job Control: Pause, resume, cancel, and delete jobs
  • Job Querying: List jobs with filtering and get specific job details
  • Statistics: Get execution statistics and performance metrics
  • Administrative: Force job evaluation and bulk operations

Installation

cd packages/tools/background-jobs-tool
npm install
npm run build

Dependencies

  • agent-core: Core agent functionality and ToolDefinition classes
  • ai: Vercel AI SDK for tool definition
  • zod: Schema validation library

Usage

Tool Actions

The tool supports the following actions through a discriminated union:

Create Job

{
  action: 'create',
  name: 'Daily Report Generator',
  cronExpression: '0 9 * * *', // Every day at 9 AM
  prompt: 'Generate and save a comprehensive daily status report',
  metadata: { // Optional
    category: 'reporting',
    priority: 'high'
  }
}

Get Specific Job

{
  action: 'get',
  jobId: 'job-12345'
}

List Jobs

{
  action: 'list',
  filters: { // Optional
    status: ['WAITING', 'RUNNING'],
    nameContains: 'report',
    dateRange: {
      start: '2024-01-01T00:00:00Z',
      end: '2024-12-31T23:59:59Z'
    }
  }
}

Update Job

{
  action: 'update',
  jobId: 'job-12345',
  updates: {
    name: 'Updated Job Name',
    cronExpression: '0 10 * * *', // Change to 10 AM
    prompt: 'Updated task description'
  }
}

Control Jobs

// Pause job
{ action: 'pause', jobId: 'job-12345' }

// Resume job
{ action: 'resume', jobId: 'job-12345' }

// Cancel job
{ action: 'cancel', jobId: 'job-12345' }

// Delete job
{ action: 'delete', jobId: 'job-12345' }

Get Statistics

{ action: 'stats' }

Administrative Actions

// Force job evaluation
{ action: 'force-eval' }

// Clear all jobs (requires confirmation)
{ action: 'clear-all', confirm: true }

CRON Expression Format

The tool supports standard 5-field CRON expressions:

┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-7, Sunday = 0 or 7)
│ │ │ │ │
* * * * *

Common Examples:

  • 0 9 * * * - Every day at 9:00 AM
  • */15 * * * * - Every 15 minutes
  • 0 */2 * * * - Every 2 hours
  • 0 9 * * 1 - Every Monday at 9:00 AM
  • 0 9 1 * * - First day of every month at 9:00 AM

Response Format

All tool actions return a consistent response format:

Success Response

{
  success: true,
  data: any, // Action-specific data
  message: string, // Human-readable success message
  timestamp: string // ISO timestamp
}

Error Response

{
  success: false,
  error: string, // Error message
  details?: string, // Additional error details
  timestamp: string // ISO timestamp
}

Integration Requirements

This tool requires the Background Jobs Plugin to be installed and registered in the agent:

  1. Plugin Dependency: The background-jobs plugin must be available
  2. Agent Integration: Add the tool to an agent's tool registry
  3. Plugin Context: Tool accesses plugin via experimental_context

Example Agent Setup

import { backgroundJobsToolDefinition } from 'background-jobs-tool';
import { BackgroundJobsPlugin } from 'background-jobs-plugin';

// Register plugin
const backgroundJobsPlugin = new BackgroundJobsPlugin(/* config */);
pluginRegistry.register(backgroundJobsPlugin);

// Register tool
toolRegistry.registerTool('background-jobs', backgroundJobsToolDefinition);

// Create agent with both plugin and tool
const agentDefinition = new AgentDefinition(
  'Agent with Background Jobs',
  'Agent that can manage scheduled tasks',
  'You can create and manage background jobs',
  ['background-jobs'], // Include tool
  'openai-gpt-4o',
  ['background-jobs'] // Include plugin
);

Testing

The tool includes comprehensive test suites:

Run Tests

# Run all tests
npm run test

# Run tests once (for CI)
npm run test:run

# Run with coverage
npm run test:coverage

# Watch mode for development
npm run test -- --watch

Test Coverage

  • Unit Tests: Core tool logic and utility functions
  • Integration Tests: Tool action handling and plugin interaction
  • Error Handling Tests: Invalid inputs and edge cases
  • Mock Strategy: Complete mock plugin for isolated testing

Error Handling

The tool implements comprehensive error handling:

  • Input Validation: CRON expression validation, required field checks
  • Plugin Availability: Graceful handling when plugin is not available
  • Action Errors: Specific error messages for each action type
  • Type Safety: Full TypeScript support with proper interfaces

Development

File Structure

src/
├── index.ts                 # Tool definition and export
├── background-jobs-tool.ts  # Core tool logic
├── types.ts                 # TypeScript interfaces
└── utils.ts                 # Utility functions

tests/
├── background-jobs-tool.test.ts # Unit tests
└── mocks.ts                     # Test mocks

Build Process

npm run build  # Compile TypeScript
npm run dev    # Watch mode for development

Contributing

Follow the project's tool development guidelines:

  1. Code Style: Follow existing TypeScript patterns
  2. Testing: Maintain comprehensive test coverage
  3. Documentation: Update README for API changes
  4. Error Handling: Use structured error objects, not exceptions

License

ISC License - Part of the Fractal Synapse project.