/ scripts / demo-immediate-invocation.js
demo-immediate-invocation.js
  1  /**
  2   * Demo: Immediate Agent Invocation
  3   *
  4   * Demonstrates event-driven agent invocation that eliminates 5-minute cron delays.
  5   *
  6   * Usage: node scripts/demo-immediate-invocation.js
  7   */
  8  
  9  import Database from 'better-sqlite3';
 10  import fs from 'fs';
 11  import { BaseAgent, resetDb as resetBaseAgentDb } from '../src/agents/base-agent.js';
 12  import {
 13    createAgentTask,
 14    getTaskById,
 15    resetDb as resetTaskManagerDb,
 16  } from '../src/agents/utils/task-manager.js';
 17  
 18  const TEST_DB = './test-immediate-demo.db';
 19  const SCHEMA_PATH = './db/schema.sql';
 20  
 21  /**
 22   * Simple test agent
 23   */
 24  class DemoAgent extends BaseAgent {
 25    constructor() {
 26      super('demo-agent', ['base.md']);
 27      // Skip context loading for demo
 28      this.context = 'Demo context';
 29      this.contextMetadata = { context: 'Demo context', sizeKB: 1, files: ['base.md'] };
 30      this.isInitialized = true;
 31    }
 32  
 33    async processTask(task) {
 34      console.log(`[DemoAgent] Processing task ${task.id}: ${task.task_type}`);
 35      this.updateTask(task.id, { result: { processed: true, timestamp: Date.now() } });
 36      await this.completeTask(task.id, { success: true });
 37    }
 38  }
 39  
 40  async function main() {
 41    console.log('='.repeat(60));
 42    console.log('Immediate Agent Invocation Demo');
 43    console.log('='.repeat(60));
 44  
 45    // Clean up old test database
 46    if (fs.existsSync(TEST_DB)) {
 47      fs.unlinkSync(TEST_DB);
 48    }
 49  
 50    // Create test database
 51    const db = new Database(TEST_DB);
 52    db.pragma('foreign_keys = ON');
 53  
 54    // Load schema
 55    const schema = fs.readFileSync(SCHEMA_PATH, 'utf8');
 56    db.exec(schema);
 57  
 58    // Set test database path
 59    process.env.DATABASE_PATH = TEST_DB;
 60  
 61    // Enable immediate invocation
 62    process.env.AGENT_IMMEDIATE_INVOCATION = 'true';
 63    process.env.AGENT_MAX_CHAIN_DEPTH = '10';
 64    process.env.AGENT_REALTIME_NOTIFICATIONS = 'false'; // Use in-process invocation
 65  
 66    // Reset database connections
 67    resetBaseAgentDb();
 68    resetTaskManagerDb();
 69  
 70    console.log('\n1. Creating agent and task...');
 71    const agent = new DemoAgent();
 72  
 73    // Mock getAgentClass to return DemoAgent
 74    agent.getAgentClass = async () => DemoAgent;
 75  
 76    console.log('2. Creating task with immediate invocation enabled...');
 77    const startTime = Date.now();
 78  
 79    const taskId = await agent.createTask({
 80      task_type: 'demo_task',
 81      assigned_to: 'demo-agent',
 82      priority: 5,
 83      context: { demo: true },
 84    });
 85  
 86    const createDuration = Date.now() - startTime;
 87  
 88    console.log(`3. Task created in ${createDuration}ms`);
 89  
 90    // Check task status
 91    const task = getTaskById(taskId);
 92  
 93    console.log('\n4. Task status:');
 94    console.log(`   - ID: ${task.id}`);
 95    console.log(`   - Status: ${task.status}`);
 96    console.log(`   - Result: ${task.result_json}`);
 97  
 98    if (task.status === 'completed') {
 99      console.log('\n✅ SUCCESS: Task was processed immediately!');
100      console.log(`   Total time: ${createDuration}ms (< 1 second)`);
101      console.log('   Without immediate invocation: 5 minutes (cron delay)');
102    } else {
103      console.log('\n❌ FAILED: Task was not processed immediately');
104      console.log(`   Status: ${task.status}`);
105    }
106  
107    // Test handoff
108    console.log('\n5. Testing handoff...');
109    const task2Id = await agent.createTask({
110      task_type: 'demo_task_2',
111      assigned_to: 'demo-agent',
112      priority: 5,
113    });
114  
115    const handoffStart = Date.now();
116    await agent.handoff(task2Id, 'demo-agent', 'Handoff test');
117    const handoffDuration = Date.now() - handoffStart;
118  
119    const task2 = getTaskById(task2Id);
120    console.log(`6. Handoff completed in ${handoffDuration}ms`);
121    console.log(`   Task status: ${task2.status}`);
122  
123    if (task2.status === 'completed') {
124      console.log('\n✅ SUCCESS: Handoff invoked receiving agent immediately!');
125    }
126  
127    // Cleanup
128    db.close();
129    fs.unlinkSync(TEST_DB);
130  
131    console.log(`\n${'='.repeat(60)}`);
132    console.log('Demo complete!');
133    console.log('='.repeat(60));
134  }
135  
136  main().catch(error => {
137    console.error('Demo failed:', error);
138    process.exit(1);
139  });