Skip to content
Shell
12.9 KB
Raw Blame
/**
 * Playwright Agent Coordinator
 *
 * Manages browser context pool for multiple concurrent agents.
 * Uses file-based locking to prevent race conditions.
 */

import * as fs from 'fs/promises';
import * as path from 'path';
import {
  CoordinatorState,
  CoordinatorConfig,
  BrowserContext,
  ReservationResult,
  ReleaseResult,
  ShareResult,
  SharedSession,
  EventLog,
} from './types';

const STATE_FILE = path.join(__dirname, 'state.json');
const LOCK_FILE = path.join(__dirname, 'state.lock');
const LOG_FILE = path.join(__dirname, 'events.log');

const DEFAULT_CONFIG: CoordinatorConfig = {
  maxContexts: 6,
  reservationTimeoutMs: 5 * 60 * 1000, // 5 minutes
  cleanupIntervalMs: 60 * 1000, // 1 minute
  lockTimeoutMs: 5000, // 5 seconds
  lockRetryDelayMs: 100,
  maxLockRetries: 50,
};

// ============================================
// File Locking (Critical for atomicity)
// ============================================

async function acquireLock(config: CoordinatorConfig): Promise<boolean> {
  const startTime = Date.now();
  let retries = 0;

  while (retries < config.maxLockRetries) {
    try {
      // Create lock file exclusively (fails if exists)
      await fs.writeFile(LOCK_FILE, JSON.stringify({
        pid: process.pid,
        timestamp: new Date().toISOString(),
      }), { flag: 'wx' });
      return true;
    } catch (err: unknown) {
      if ((err as NodeJS.ErrnoException).code === 'EEXIST') {
        // Lock exists - check if stale
        try {
          const lockData = await fs.readFile(LOCK_FILE, 'utf-8');
          const lock = JSON.parse(lockData);
          const lockAge = Date.now() - new Date(lock.timestamp).getTime();

          // Stale lock (> 30 seconds) - remove it
          if (lockAge > 30000) {
            await fs.unlink(LOCK_FILE);
            continue;
          }
        } catch {
          // Lock file corrupted, remove it
          try { await fs.unlink(LOCK_FILE); } catch { /* ignore */ }
        }

        // Wait and retry
        await sleep(config.lockRetryDelayMs + Math.random() * 50);
        retries++;
      } else {
        throw err;
      }
    }

    if (Date.now() - startTime > config.lockTimeoutMs) {
      return false;
    }
  }

  return false;
}

async function releaseLock(): Promise<void> {
  try {
    await fs.unlink(LOCK_FILE);
  } catch {
    // Already released or never acquired
  }
}

function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// ============================================
// State Management
// ============================================

function createDefaultState(): CoordinatorState {
  const contexts: Record<string, BrowserContext> = {};

  for (let i = 1; i <= DEFAULT_CONFIG.maxContexts; i++) {
    contexts[`context_${i}`] = {
      id: `context_${i}`,
      status: 'available',
      agentId: null,
      reservedAt: null,
      purpose: null,
      lastActivity: null,
    };
  }

  return {
    version: 1,
    updatedAt: new Date().toISOString(),
    config: DEFAULT_CONFIG,
    contexts,
    sharedSessions: {},
    waitingAgents: [],
  };
}

async function loadState(): Promise<CoordinatorState> {
  try {
    const data = await fs.readFile(STATE_FILE, 'utf-8');
    return JSON.parse(data);
  } catch (err: unknown) {
    if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
      const defaultState = createDefaultState();
      await saveState(defaultState);
      return defaultState;
    }
    throw err;
  }
}

async function saveState(state: CoordinatorState): Promise<void> {
  state.updatedAt = new Date().toISOString();
  state.version++;
  await fs.writeFile(STATE_FILE, JSON.stringify(state, null, 2));
}

async function logEvent(event: EventLog['event']): Promise<void> {
  const entry: EventLog = {
    timestamp: new Date().toISOString(),
    event,
  };
  await fs.appendFile(LOG_FILE, JSON.stringify(entry) + '\n');
}

// ============================================
// Core Operations
// ============================================

/**
 * Reserve a browser context for exclusive use
 */
export async function reserveContext(
  agentId: string,
  purpose: string
): Promise<ReservationResult> {
  const locked = await acquireLock(DEFAULT_CONFIG);
  if (!locked) {
    return { success: false, error: 'Could not acquire lock - try again' };
  }

  try {
    const state = await loadState();

    // Clean up stale reservations first
    await cleanupStaleReservations(state);

    // Check if agent already has a context
    const existingContext = Object.values(state.contexts).find(
      ctx => ctx.agentId === agentId && ctx.status === 'reserved'
    );
    if (existingContext) {
      return {
        success: true,
        contextId: existingContext.id,
        error: 'Already have a reserved context',
      };
    }

    // Find an available context
    const available = Object.values(state.contexts).find(
      ctx => ctx.status === 'available'
    );

    if (!available) {
      // Add to waiting list
      const alreadyWaiting = state.waitingAgents.some(w => w.agentId === agentId);
      if (!alreadyWaiting) {
        state.waitingAgents.push({
          agentId,
          requestedAt: new Date().toISOString(),
          purpose,
          priority: 'normal',
        });
        await saveState(state);
      }

      const position = state.waitingAgents.findIndex(w => w.agentId === agentId) + 1;
      return {
        success: false,
        error: 'No contexts available',
        waitPosition: position,
        estimatedWaitMs: position * 60000, // ~1 min per position
      };
    }

    // Reserve the context
    available.status = 'reserved';
    available.agentId = agentId;
    available.reservedAt = new Date().toISOString();
    available.purpose = purpose;
    available.lastActivity = new Date().toISOString();

    // Remove from waiting list if present
    state.waitingAgents = state.waitingAgents.filter(w => w.agentId !== agentId);

    await saveState(state);
    await logEvent({ type: 'reserved', agentId, contextId: available.id, purpose });

    return { success: true, contextId: available.id };
  } finally {
    await releaseLock();
  }
}

/**
 * Release a browser context back to the pool
 */
export async function releaseContext(agentId: string): Promise<ReleaseResult> {
  const locked = await acquireLock(DEFAULT_CONFIG);
  if (!locked) {
    return { success: false, error: 'Could not acquire lock - try again' };
  }

  try {
    const state = await loadState();

    const context = Object.values(state.contexts).find(
      ctx => ctx.agentId === agentId
    );

    if (!context) {
      return { success: false, error: 'No context found for this agent' };
    }

    const contextId = context.id;

    // Clean up any shared sessions for this context
    const sessionsToRemove = Object.entries(state.sharedSessions)
      .filter(([, session]) => session.contextId === contextId)
      .map(([id]) => id);

    for (const sessionId of sessionsToRemove) {
      delete state.sharedSessions[sessionId];
    }

    // Reset the context
    context.status = 'available';
    context.agentId = null;
    context.reservedAt = null;
    context.purpose = null;
    context.lastActivity = null;

    // Notify next waiting agent (they'll need to re-request)
    if (state.waitingAgents.length > 0) {
      const nextAgent = state.waitingAgents[0];
      console.log(`[Coordinator] Context available - next in queue: ${nextAgent.agentId}`);
    }

    await saveState(state);
    await logEvent({ type: 'released', agentId, contextId });

    return { success: true, contextId };
  } finally {
    await releaseLock();
  }
}

/**
 * Share a context with another agent
 */
export async function shareContext(
  ownerAgentId: string,
  targetAgentId: string,
  expiresInMs?: number
): Promise<ShareResult> {
  const locked = await acquireLock(DEFAULT_CONFIG);
  if (!locked) {
    return { success: false, error: 'Could not acquire lock - try again' };
  }

  try {
    const state = await loadState();

    // Find owner's context
    const context = Object.values(state.contexts).find(
      ctx => ctx.agentId === ownerAgentId && ctx.status === 'reserved'
    );

    if (!context) {
      return { success: false, error: 'Owner does not have a reserved context' };
    }

    // Create shared session
    const sessionId = `share_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
    const session: SharedSession = {
      sessionId,
      contextId: context.id,
      ownerAgentId,
      allowedAgentIds: [targetAgentId],
      createdAt: new Date().toISOString(),
      expiresAt: expiresInMs
        ? new Date(Date.now() + expiresInMs).toISOString()
        : null,
    };

    // Mark context as shared
    context.status = 'shared';
    state.sharedSessions[sessionId] = session;

    await saveState(state);
    await logEvent({ type: 'shared', ownerAgentId, targetAgentId, sessionId });

    return { success: true, sessionId };
  } finally {
    await releaseLock();
  }
}

/**
 * Update activity timestamp (heartbeat)
 */
export async function heartbeat(agentId: string): Promise<boolean> {
  const locked = await acquireLock(DEFAULT_CONFIG);
  if (!locked) return false;

  try {
    const state = await loadState();
    const context = Object.values(state.contexts).find(
      ctx => ctx.agentId === agentId
    );

    if (context) {
      context.lastActivity = new Date().toISOString();
      await saveState(state);
      return true;
    }
    return false;
  } finally {
    await releaseLock();
  }
}

/**
 * Get current pool status
 */
export async function getStatus(): Promise<{
  available: number;
  reserved: number;
  shared: number;
  waiting: number;
  contexts: BrowserContext[];
}> {
  const state = await loadState();
  const contexts = Object.values(state.contexts);

  return {
    available: contexts.filter(c => c.status === 'available').length,
    reserved: contexts.filter(c => c.status === 'reserved').length,
    shared: contexts.filter(c => c.status === 'shared').length,
    waiting: state.waitingAgents.length,
    contexts,
  };
}

/**
 * Check if an agent can use a context (own or shared)
 */
export async function canUseContext(agentId: string): Promise<{
  canUse: boolean;
  contextId?: string;
  isShared: boolean;
}> {
  const state = await loadState();

  // Check if agent owns a context
  const ownedContext = Object.values(state.contexts).find(
    ctx => ctx.agentId === agentId
  );
  if (ownedContext) {
    return { canUse: true, contextId: ownedContext.id, isShared: false };
  }

  // Check if agent has access via shared session
  const sharedSession = Object.values(state.sharedSessions).find(
    session => session.allowedAgentIds.includes(agentId) &&
      (!session.expiresAt || new Date(session.expiresAt) > new Date())
  );
  if (sharedSession) {
    return { canUse: true, contextId: sharedSession.contextId, isShared: true };
  }

  return { canUse: false, isShared: false };
}

// ============================================
// Cleanup
// ============================================

async function cleanupStaleReservations(state: CoordinatorState): Promise<void> {
  const now = Date.now();
  const staleContexts: string[] = [];

  for (const context of Object.values(state.contexts)) {
    if (context.status !== 'available' && context.lastActivity) {
      const lastActivity = new Date(context.lastActivity).getTime();
      const age = now - lastActivity;

      // Stale if no activity for 2x the timeout
      if (age > state.config.reservationTimeoutMs * 2) {
        staleContexts.push(context.id);
        context.status = 'available';
        context.agentId = null;
        context.reservedAt = null;
        context.purpose = null;
        context.lastActivity = null;
      }
    }
  }

  // Clean expired shared sessions
  for (const [sessionId, session] of Object.entries(state.sharedSessions)) {
    if (session.expiresAt && new Date(session.expiresAt) < new Date()) {
      delete state.sharedSessions[sessionId];
    }
  }

  if (staleContexts.length > 0) {
    await logEvent({ type: 'cleanup', staleContexts });
  }
}

/**
 * Force release all contexts for an agent (emergency cleanup)
 */
export async function forceReleaseAll(agentId: string): Promise<number> {
  const locked = await acquireLock(DEFAULT_CONFIG);
  if (!locked) return 0;

  try {
    const state = await loadState();
    let released = 0;

    for (const context of Object.values(state.contexts)) {
      if (context.agentId === agentId) {
        context.status = 'available';
        context.agentId = null;
        context.reservedAt = null;
        context.purpose = null;
        context.lastActivity = null;
        released++;
      }
    }

    // Remove from waiting list
    state.waitingAgents = state.waitingAgents.filter(w => w.agentId !== agentId);

    // Remove shared sessions
    for (const [sessionId, session] of Object.entries(state.sharedSessions)) {
      if (session.ownerAgentId === agentId) {
        delete state.sharedSessions[sessionId];
      }
    }

    await saveState(state);
    return released;
  } finally {
    await releaseLock();
  }
}