Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

2.4 KB
Raw Blame
import debug from 'debug';
import type { Context } from 'hono';

import { getServerDB } from '@/database/core/db-adaptor';
import { StaleOperationReaper } from '@/server/services/agentRuntime';
import { recoverChannels } from '@/server/services/channel/recover';

const log = debug('lobe-server:agent:reap-operations');

/**
 * Vercel cron entry point for recovering operations whose executing host died
 * mid-step β€” see {@link StaleOperationReaper}.
 *
 * Auth: `bearerSecretAuth(CRON_SECRET)` on the route, matching the existing
 * `/api/agent/gateway` cron.
 *
 * Query params (all optional, mainly for manual runs and incident response):
 * - `staleAfterMs` β€” override the lease window
 * - `limit` β€” cap the operations examined in this tick
 * - `maxRedriveAttempts` β€” override the per-operation redrive budget
 */
export async function reapOperations(c: Context): Promise<Response> {
  const startedAt = Date.now();

  const num = (name: string): number | undefined => {
    const raw = c.req.query(name);
    if (raw === undefined) return undefined;
    const parsed = Number(raw);
    return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
  };

  try {
    const serverDB = await getServerDB();
    await recoverChannels(serverDB);
    const result = await new StaleOperationReaper(serverDB).sweep({
      limit: num('limit'),
      maxRedriveAttempts: num('maxRedriveAttempts'),
      staleAfterMs: num('staleAfterMs'),
    });

    log('sweep completed in %dms: %O', Date.now() - startedAt, result);

    // A tick where every candidate failed is an outage (Redis, database or
    // queue down), not a quiet sweep: answer 5xx so cron monitoring alerts while
    // the operations stay stuck. A partial failure is one poisoned row among
    // healthy recoveries, so it stays 2xx but still reports `success: false`.
    const allFailed = result.examined > 0 && result.failed === result.examined;
    if (result.failed > 0)
      console.error('[reap-operations] %d candidate(s) failed: %O', result.failed, result);

    return c.json(
      { ...result, executionTime: Date.now() - startedAt, success: result.failed === 0 },
      allFailed ? 500 : 200,
    );
  } catch (error) {
    const message = error instanceof Error ? error.message : 'unknown error';
    console.error('[reap-operations] %O', error);

    return c.json({ error: message, executionTime: Date.now() - startedAt, success: false }, 500);
  }
}