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.

9.1 KB
Raw Blame
import type { GoalItem, TaskItem } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';

import { AgentOperationModel } from '@/database/models/agentOperation';
import { GoalModel } from '@/database/models/goal';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import type { LobeChatDatabase } from '@/database/type';
import { TaskRunnerService } from '@/server/services/taskRunner';

import { clearDeviceDispatchStreak, parkDeviceUnavailableDispatch } from './deviceDispatchStreak';
import {
  countChargedTaskAttempts,
  countUnchargedRuns,
  isDeviceUnavailableFailure,
  resolveTaskAttemptBudget,
  resolveTaskMaxSteps,
} from './recoveryPolicy';
import { statusAuthoredByActor } from './supervisor/policy';
import { claimGoalTask } from './taskClaim';

const log = debug('lobe-server:goal-task-recovery');

/**
 * Goal statuses under which no recovery may start a run. `close` fences a goal
 * by pausing it under its row lock before scanning live runs, so a recovery
 * claim has to recheck the goal under that same lock.
 */
const GOAL_FENCED_STATUSES = new Set(['paused', 'achieved', 'failed', 'canceled']);

export type TaskRecoveryOutcome =
  /** This call spawned the retry, and `operationId` is its run. */
  | 'started'
  /** Another overlapping advance owns the retry; this one started nothing. */
  | 'already-running'
  /** Someone settled the Task while this recovery was being decided. */
  | 'settled'
  /** The goal was paused or ended (e.g. being closed) before the claim. */
  | 'goal-stopped'
  | 'exhausted-cost'
  | 'exhausted-rounds'
  | 'spawn-failed';

/**
 * `started` and `already-running` both mean "the Task is moving, keep waiting",
 * but only the first is something *this* advance did. They used to share the
 * name `continued`, which made the trajectory claim a run it had not started
 * and drop the operation id of the one it had.
 */
export interface TaskRecoveryResult {
  /** Present only on `spawn-failed` when the retry could not reach its device. */
  deviceUnavailable?: boolean;
  /**
   * Present only on `spawn-failed`: why the run did not start, when the cause is
   * one the person answering the gate can act on (see {@link describeSpawnFailure}).
   */
  error?: string;
  /** Present only on `started`. The drill-down link into `agent_operations`. */
  operationId?: string;
  outcome: TaskRecoveryOutcome;
}

/** Longest spawn failure carried into a gate reason. */
const MAX_SPAWN_FAILURE_LENGTH = 300;

/**
 * The part of a spawn failure that may reach the person answering the gate.
 *
 * The gate used to say only that recovery "could not start the next attempt",
 * so its owner asked what had gone wrong and pressed Retry blind. `runTask`
 * refuses with a TRPC error written for its caller β€” a running topic it names,
 * a missing agent β€” and that sentence is what they need. Any other error may
 * carry SQL, identifiers or provider diagnostics; it stays in the server log.
 */
export const describeSpawnFailure = (error: unknown): string | undefined => {
  if (!(error instanceof TRPCError) || error.code === 'INTERNAL_SERVER_ERROR') return;
  const message = error.message.trim().replace(/\.$/, '');
  if (!message) return;
  return message.length > MAX_SPAWN_FAILURE_LENGTH
    ? `${message.slice(0, MAX_SPAWN_FAILURE_LENGTH - 1)}…`
    : message;
};

/** Retry budget and spawn boundary for a Goal Graph Task. */
export class TaskRecoveryCoordinator {
  constructor(
    private readonly db: LobeChatDatabase,
    private readonly userId: string,
    private readonly workspaceId?: string,
  ) {}

  recover = async (params: {
    goal: GoalItem;
    spentCost?: number;
    task: TaskItem;
  }): Promise<TaskRecoveryResult> => {
    const { goal, task } = params;
    // A run lost to a machine problem was never judged, so it does not spend the
    // budget; the coordinator's offline / quota / transient schedules bound those
    // retries instead.
    const runs = await new TaskTopicModel(this.db, this.userId, this.workspaceId).findByTaskId(
      task.id,
    );
    const attempts = countChargedTaskAttempts(task, countUnchargedRuns(runs));
    const attemptBudget = resolveTaskAttemptBudget(goal);
    if (attempts >= attemptBudget) return { outcome: 'exhausted-rounds' };

    if (typeof goal.maxTotalCost === 'number') {
      const spent =
        params.spentCost ??
        (await new AgentOperationModel(this.db, this.userId, this.workspaceId).sumCostByTask(
          task.id,
        ));
      if (spent >= goal.maxTotalCost) return { outcome: 'exhausted-cost' };
    }

    // Both recovery paths β€” a failed verification and an abandoned operation β€”
    // reach here from `tick`, and advances overlap: an event hook, a manual
    // nudge, the sweep. `runTask` decides whether a run is in flight by reading
    // the task's topics before creating one, so without this claim two
    // coordinators would each spawn a paid retry of the same Task.
    //
    // Both paths hand us a task row read before they paused it, so the claim
    // has to compare against what the row says now. A task already `running`
    // is one another advance has claimed β€” leave it to that one.
    const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);
    const current = await taskModel.findById(task.id);
    if (!current || current.status === 'running') {
      log('task %s recovery was already claimed by another advance', task.identifier);
      return { outcome: 'already-running' };
    }
    // Both branches that route here require `paused`, so that is the only status this
    // claim may take. The tick read the Task before it decided; claiming whatever it
    // holds now would swap somebody's completion, cancellation or explicit failure to
    // `running` and start a paid run over their decision.
    if (current.status !== 'paused') {
      log(
        'task %s moved to %s before the claim; leaving it alone',
        task.identifier,
        current.status,
      );
      return { outcome: 'settled' };
    }
    // A pause somebody made is theirs. The routing error survives a manual round trip
    // through another status, because the status update keeps the old error when none
    // is supplied, so the status alone cannot say whose pause this is.
    if (statusAuthoredByActor(await taskModel.getActivities(task.id, 20), current.status)) {
      log('task %s was paused by an actor; leaving it alone', task.identifier);
      return { outcome: 'settled' };
    }
    // Claimed under the goal row lock, like `dispatchWork`: the tick decided on
    // a goal snapshot, and a `close` may have fenced the goal (paused it) since.
    // Claiming after that fence would start a run its running-topic scan never
    // sees, and the goal would then be closed over a run still spending.
    const claimed = await this.db.transaction(async (tx) => {
      const currentGoal = await new GoalModel(tx, this.userId, this.workspaceId).lockById(goal.id);
      if (!currentGoal || GOAL_FENCED_STATUSES.has(currentGoal.status)) return 'goal-stopped';
      return claimGoalTask(
        new TaskModel(tx, this.userId, this.workspaceId),
        { id: task.id, status: 'paused' },
        'running',
        { error: null, startedAt: new Date() },
      );
    });
    if (claimed === 'goal-stopped') {
      log('task %s recovery skipped: goal %s is no longer running', task.identifier, goal.id);
      return { outcome: 'goal-stopped' };
    }
    if (!claimed) {
      log('task %s recovery lost the claim race', task.identifier);
      return { outcome: 'already-running' };
    }

    try {
      const run = await new TaskRunnerService(this.db, this.userId, this.workspaceId).runTask({
        maxSteps: resolveTaskMaxSteps(goal),
        taskId: task.id,
        trigger: 'goal',
      });
      log('task %s β†’ recovery attempt %d spawned', task.identifier, attempts + 1);
      await clearDeviceDispatchStreak(taskModel, current.id).catch((clearError) => {
        log('task %s failed to clear the device dispatch streak: %O', task.identifier, clearError);
      });
      return { operationId: run.operationId, outcome: 'started' };
    } catch (error) {
      log('task %s recovery spawn failed (non-fatal): %O', task.identifier, error);
      // A retry that could not reach its device keeps that reason, so the next
      // advance waits for the device instead of retrying into the same failure.
      const message = error instanceof Error ? error.message : String(error);
      const deviceUnavailable = isDeviceUnavailableFailure(message);
      // We own the claim, so nothing else will put the task back.
      await (
        deviceUnavailable
          ? parkDeviceUnavailableDispatch(taskModel, current, message)
          : taskModel.updateStatusIfCurrent(task.id, 'running', 'paused', { error: current.error })
      ).catch((releaseError) => {
        log('task %s failed to release the recovery claim: %O', task.identifier, releaseError);
      });
      return {
        deviceUnavailable,
        error: deviceUnavailable ? undefined : describeSpawnFailure(error),
        outcome: 'spawn-failed',
      };
    }
  };
}