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.

44.0 KB
Raw Blame
import {
  type AgentOperationCompletionReason,
  type AgentOperationStatus,
  isServerDefaultHeterogeneousRelayInvocation,
  type ServerDefaultHeterogeneousRelayInvocation,
  type VerifyRunStatus,
} from '@lobechat/types';
import { and, desc, eq, gte, inArray, isNotNull, or, sql } from 'drizzle-orm';

import { today } from '@/utils/time';

import type {
  AgentOperationAppContext,
  AgentOperationError,
  AgentOperationInterruption,
  NewAgentOperation,
} from '../schemas/agentOperations';
import { agentOperations } from '../schemas/agentOperations';
import type { LobeChatDatabase } from '../type';
import { notShareVisitorTopicRef } from '../utils/shareVisitor';
import { buildWorkspaceWhere } from '../utils/workspace';
import { findLiveTopicOperations, findScopedOperation } from './agentOperationQueries';

/**
 * Verify rollup states. Aliases the single `VerifyRunStatus` source of truth in
 * `@lobechat/types` (which also backs the `verify_status` column enum and
 * `verify_runs.status`) so the three never drift.
 */
export type VerifyStatus = VerifyRunStatus;

/**
 * Provenance of an abandonment claim, persisted under `metadata.abandonment`.
 *
 * Three phases rather than a boolean because the windows that matter are the
 * ones *between* them: `claimed` means a watchdog retired the row and still
 * owes the conversation its side effects, so a retry must finish the job;
 * `handoff_pending` means those side effects landed but the caller still has to
 * hand the sub-agent's parent over to a resume, so a retry replays only that
 * step; `finalized` means everything landed and a retry must leave the row
 * alone.
 */
export interface AgentAbandonmentMark {
  /** ISO timestamp of the claim; absent on the `finalized` rewrite. */
  at?: string;
  /**
   * Linkage for the parent-resume hand-off this abandonment still owes. Kept
   * durable so a retry can replay the hand-off after the finalising host dies,
   * instead of stranding the parent in `waiting_for_async_tool`.
   */
  handoff?: Record<string, unknown>;
  phase: 'claimed' | 'finalized' | 'handoff_pending';
  reason?: string;
}

export interface RecordOperationStartParams {
  agentId?: string | null;
  appContext?: AgentOperationAppContext;
  chatGroupId?: string | null;
  maxSteps?: number;
  /**
   * Durable per-run metadata persisted on the operation row (jsonb). Carries the
   * Agent Signal run marker so server-side tools can read it back from the row
   * (`metadata.agentSignal`) at tool-call time.
   */
  metadata?: Record<string, unknown>;
  model?: string;
  modelRuntimeConfig?: Record<string, unknown>;
  operationId: string;
  parentOperationId?: string | null;
  provider?: string;
  /** Trusted trigger dispatch: atomically consume an existing matching idle reservation. */
  requireReservation?: boolean;
  startedAt?: Date;
  taskId?: string | null;
  threadId?: string | null;
  topicId?: string | null;
  trigger?: string;
}

export interface AgentInterventionDispatchMarker {
  deduplicationId: string;
  messageId: string;
  resolutionRequestId: string;
  scheduledAt: string;
  state: 'scheduled';
}

export interface AgentInterventionPreparationMarker {
  deduplicationId: string;
  resolutionRequestId: string;
  state: 'ready';
  stepIndex: number;
}

/** Why `heteroIngest` refused a batch β€” see {@link HeteroIngestRejectionMarker}. */
export type HeteroIngestRejectionReason = 'operation-not-running' | 'stale-operation';

/**
 * Stamped the first time `heteroIngest` refuses a batch for this operation.
 *
 * Both refusal paths (the op row is no longer `running`, or the topic's
 * `runningOperation` marker no longer names this op) mean the producer's
 * remaining output is being discarded while its CLI keeps running happily. The
 * marker is what carries that fact across to `heteroFinish`, which would
 * otherwise settle the producer's `success` receipt as a clean turn and leave
 * the user staring at an assistant placeholder that never fills in.
 */
export interface HeteroIngestRejectionMarker {
  at: string;
  /** Events discarded with the refusal that stamped this marker. */
  droppedEvents: number;
  reason: HeteroIngestRejectionReason;
}

const sameServerDefaultRelayInvocation = (
  left: ServerDefaultHeterogeneousRelayInvocation,
  right: ServerDefaultHeterogeneousRelayInvocation,
): boolean =>
  left.agentType === right.agentType &&
  left.ingress === right.ingress &&
  left.model === right.model &&
  left.operationId === right.operationId &&
  left.provider === right.provider;

/** Terminal usage summed across every child operation of one parent. All-zero when it has none. */
export interface ChildUsageRollup {
  llmCalls: number;
  toolCalls: number;
  totalCost: number;
  totalInputTokens: number;
  totalOutputTokens: number;
  totalTokens: number;
}

export interface RecordOperationCompletionParams {
  completedAt?: Date;
  completionReason?: AgentOperationCompletionReason;
  cost?: Record<string, unknown> | null;
  error?: AgentOperationError | null;
  interruption?: AgentOperationInterruption | null;
  llmCalls?: number | null;
  /** Backfill the executed model when it's only known at completion (e.g. a
   * heterogeneous run learns its real model from the CLI mid-stream). Omit to
   * keep the value seeded at `recordStart`. */
  model?: string | null;
  processingTimeMs?: number | null;
  /** Backfill the executed provider β€” see {@link RecordOperationCompletionParams.model}. */
  provider?: string | null;
  status: Exclude<AgentOperationStatus, 'idle'>;
  stepCount?: number | null;
  toolCalls?: number | null;
  totalCost?: number | null;
  totalInputTokens?: number | null;
  totalOutputTokens?: number | null;
  totalTokens?: number | null;
  traceS3Key?: string | null;
  usage?: Record<string, unknown> | null;
}

export class AgentOperationModel {
  private readonly db: LobeChatDatabase;
  private readonly userId: string;
  private readonly workspaceId?: string;

  constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
    this.db = db;
    this.userId = userId;
    this.workspaceId = workspaceId;
  }

  private ownership = () =>
    buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentOperations);

  /**
   * Insert the initial row when an operation is created. Idempotent via
   * the primary key; only an idle reservation with the same identity may be initialized.
   */
  async recordStart(params: RecordOperationStartParams): Promise<void> {
    const values: NewAgentOperation = {
      agentId: params.agentId ?? null,
      appContext: params.appContext,
      chatGroupId: params.chatGroupId ?? null,
      id: params.operationId,
      maxSteps: params.maxSteps,
      ...(params.metadata ? { metadata: params.metadata } : {}),
      model: params.model,
      modelRuntimeConfig: params.modelRuntimeConfig,
      parentOperationId: params.parentOperationId ?? null,
      provider: params.provider,
      startedAt: params.startedAt ?? new Date(),
      status: 'running',
      taskId: params.taskId ?? null,
      threadId: params.threadId ?? null,
      topicId: params.topicId ?? null,
      trigger: params.trigger,
      userId: this.userId,
      workspaceId: this.workspaceId ?? null,
    };

    const reservationIdentity = and(
      eq(agentOperations.id, params.operationId),
      eq(agentOperations.status, 'idle'),
      eq(agentOperations.userId, this.userId),
      sql`${agentOperations.workspaceId} IS NOT DISTINCT FROM ${this.workspaceId ?? null}`,
      sql`${agentOperations.topicId} IS NOT DISTINCT FROM ${params.topicId ?? null}`,
      sql`${agentOperations.agentId} IS NOT DISTINCT FROM ${params.agentId ?? null}`,
    );
    if (params.requireReservation) {
      const [started] = await this.db
        .update(agentOperations)
        .set({
          ...values,
          ...(params.metadata && {
            metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify(params.metadata)}::jsonb`,
          }),
        })
        .where(reservationIdentity)
        .returning({ id: agentOperations.id });
      if (!started) throw new Error('Operation reservation is no longer available');
      return;
    }

    // A trigger may reserve an idle operation before dispatch. Only the same execution
    // identity may initialize it; duplicate starts never overwrite a running or terminal row.
    await this.db
      .insert(agentOperations)
      .values(values)
      .onConflictDoUpdate({
        target: agentOperations.id,
        set: values,
        setWhere: and(
          eq(agentOperations.status, 'idle'),
          eq(agentOperations.userId, this.userId),
          sql`${agentOperations.workspaceId} IS NOT DISTINCT FROM ${this.workspaceId ?? null}`,
          sql`${agentOperations.topicId} IS NOT DISTINCT FROM ${params.topicId ?? null}`,
          sql`${agentOperations.agentId} IS NOT DISTINCT FROM ${params.agentId ?? null}`,
        ),
      });
  }

  /**
   * Newest operation in this topic that is parked waiting for tool approval.
   *
   * A parked run is stream-terminal, so the client marks its own operation
   * completed and prunes it β€” by the time the user decides to stop, only the
   * DB still knows which operation is holding the turn. Scoped by `userId` so
   * one user can never resolve (and then terminate) another's run.
   */
  async findLatestParkedOperationId(topicId: string): Promise<string | undefined> {
    const [row] = await this.db
      .select({ id: agentOperations.id })
      .from(agentOperations)
      .where(
        and(
          eq(agentOperations.topicId, topicId),
          eq(agentOperations.userId, this.userId),
          eq(agentOperations.status, 'waiting_for_human'),
        ),
      )
      .orderBy(sql`${agentOperations.createdAt} desc`)
      .limit(1);

    return row?.id;
  }

  /**
   * Update the row when the operation reaches a terminal state. Scoped by
   * `userId` so a leaked operationId can't be used to flip another user's
   * row. No-op when the start row was never written.
   *
   * Returns the written row's provenance and the status it held before this write, so a caller
   * can act once per transition: a replay of the same terminal status is accepted again and
   * reads back that status. `undefined` when nothing was written.
   */
  async recordCompletion(operationId: string, params: RecordOperationCompletionParams) {
    const updates: Partial<NewAgentOperation> = {
      completionReason: params.completionReason,
      status: params.status,
    };

    // Only set completedAt when explicitly provided so callers can mark a
    // non-terminal status (e.g. waiting_for_human) without falsely stamping
    // completion time.
    if (params.completedAt !== undefined) updates.completedAt = params.completedAt;
    if (params.processingTimeMs !== undefined) updates.processingTimeMs = params.processingTimeMs;
    if (params.stepCount !== undefined) updates.stepCount = params.stepCount;
    if (params.totalCost !== undefined) updates.totalCost = params.totalCost;
    if (params.totalTokens !== undefined) updates.totalTokens = params.totalTokens;
    if (params.totalInputTokens !== undefined) updates.totalInputTokens = params.totalInputTokens;
    if (params.totalOutputTokens !== undefined)
      updates.totalOutputTokens = params.totalOutputTokens;
    if (params.llmCalls !== undefined) updates.llmCalls = params.llmCalls;
    if (params.toolCalls !== undefined) updates.toolCalls = params.toolCalls;
    if (params.model !== undefined) updates.model = params.model;
    if (params.provider !== undefined) updates.provider = params.provider;
    if (params.cost !== undefined) updates.cost = params.cost;
    if (params.usage !== undefined) updates.usage = params.usage;
    if (params.error !== undefined) updates.error = params.error;
    if (params.interruption !== undefined) updates.interruption = params.interruption;
    if (params.traceS3Key !== undefined) updates.traceS3Key = params.traceS3Key;

    return this.db.transaction(async (tx) => {
      // Lock the row before reading its status: two overlapping terminal writes would otherwise
      // both read the status from before either committed, and both look like the first one.
      const [previous] = await tx
        .select({ status: agentOperations.status })
        .from(agentOperations)
        .where(and(eq(agentOperations.id, operationId), this.ownership()))
        .for('update');
      if (!previous) return undefined;

      const [row] = await tx
        .update(agentOperations)
        .set(updates)
        .where(
          and(
            eq(agentOperations.id, operationId),
            or(
              inArray(agentOperations.status, [
                'running',
                'waiting_for_human',
                'waiting_for_async_tool',
                'waiting_for_client',
              ]),
              eq(agentOperations.status, params.status),
            ),
            this.ownership(),
          ),
        )
        .returning({
          id: agentOperations.id,
          parentOperationId: agentOperations.parentOperationId,
          trigger: agentOperations.trigger,
        });

      return row && { ...row, previousStatus: previous.status };
    });
  }

  /**
   * Persist provider enqueue acknowledgement without replacing other runtime
   * metadata. The provenance request id is checked in SQL so a stale/colliding
   * operation can never be marked scheduled by another intervention.
   */
  async recordAgentInterventionDispatch(
    operationId: string,
    marker: AgentInterventionDispatchMarker,
  ): Promise<boolean> {
    const [row] = await this.db
      .update(agentOperations)
      .set({
        metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ agentInterventionDispatch: marker })}::jsonb`,
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          this.ownership(),
          sql`${agentOperations.metadata}->'agentInterventionContinuation'->>'resolutionRequestId' = ${marker.resolutionRequestId}`,
        ),
      )
      .returning({ id: agentOperations.id });
    return Boolean(row);
  }

  /**
   * Persist the crash-recovery boundary after runtime state and serialized
   * hooks are complete, but before the first queue publish. A missing runtime
   * state with this marker is therefore ambiguous (it may already have run)
   * and must never be rebuilt from scratch.
   */
  async recordAgentInterventionPreparation(
    operationId: string,
    marker: AgentInterventionPreparationMarker,
  ): Promise<boolean> {
    const [row] = await this.db
      .update(agentOperations)
      .set({
        metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ agentInterventionPreparation: marker })}::jsonb`,
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          this.ownership(),
          sql`${agentOperations.metadata}->'agentInterventionContinuation'->>'resolutionRequestId' = ${marker.resolutionRequestId}`,
        ),
      )
      .returning({ id: agentOperations.id });
    return Boolean(row);
  }

  /**
   * Record the first official-relay acceptance for a server-default operation.
   * Matching retries reuse the original timestamp; a conflicting selection or
   * terminal operation fails closed.
   */
  async recordServerDefaultRelayInvocation(
    operationId: string,
    invocation: ServerDefaultHeterogeneousRelayInvocation,
  ): Promise<ServerDefaultHeterogeneousRelayInvocation | null> {
    if (operationId !== invocation.operationId) return null;

    const [row] = await this.db
      .update(agentOperations)
      .set({
        metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ serverDefaultRelayInvocation: invocation })}::jsonb`,
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          eq(agentOperations.status, 'running'),
          eq(agentOperations.model, invocation.model),
          eq(agentOperations.provider, invocation.provider),
          this.ownership(),
          sql`${agentOperations.metadata}->>'serverDefaultHeterogeneous' = 'true'`,
          sql`${agentOperations.metadata}->>'agentType' = ${invocation.agentType}`,
          sql`NOT COALESCE(jsonb_exists(${agentOperations.metadata}, 'serverDefaultRelayInvocation'), false)`,
        ),
      )
      .returning({ metadata: agentOperations.metadata });

    if (row) return invocation;

    const existing = (await this.findById(operationId))?.metadata?.serverDefaultRelayInvocation;
    return isServerDefaultHeterogeneousRelayInvocation(existing) &&
      sameServerDefaultRelayInvocation(existing, invocation)
      ? existing
      : null;
  }

  /** A rejected publish must never be resurrected by stale recovery. */
  async recordDispatchFailure(operationId: string, message: string): Promise<boolean> {
    const [row] = await this.db
      .update(agentOperations)
      .set({
        completedAt: new Date(),
        completionReason: 'error',
        error: { message, type: 'QueueDispatchError' },
        status: 'error',
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          eq(agentOperations.status, 'running'),
          this.ownership(),
        ),
      )
      .returning({ id: agentOperations.id });

    return Boolean(row);
  }

  /** Idempotently settle a running operation without rewriting an existing terminal outcome. */
  async settleRunning(
    operationId: string,
    status: 'done' | 'error' | 'interrupted',
  ): Promise<boolean> {
    return this.settleFrom(operationId, status, ['running']);
  }

  /**
   * Like {@link settleRunning}, but also retires a row parked in
   * `waiting_for_human` / `waiting_for_async_tool`. For callers that already
   * know the run is dead: a parked row whose runtime was abandoned has nothing
   * left that could ever resume it.
   */
  async settleLive(
    operationId: string,
    status: 'done' | 'error' | 'interrupted',
  ): Promise<boolean> {
    return this.settleFrom(operationId, status, [
      'running',
      'waiting_for_human',
      'waiting_for_async_tool',
      'waiting_for_client',
    ]);
  }

  /**
   * Claim a live row for an abandonment, atomically recording that the claim
   * exists.
   *
   * `settleLive` alone cannot say *who* retired the row, so a finalisation that
   * dies after the claim but before its side effects leaves a row that looks
   * exactly like a run which failed on its own β€” and the second invocation then
   * reads it as "already settled" and gives up. Stamping `metadata.abandonment`
   * in the same UPDATE keeps the claim and its provenance inseparable: a retry
   * can tell a half-finished abandonment (`phase: 'claimed'`) from a foreign or
   * completed terminal row, and pick the finalisation back up.
   */
  async claimForAbandonment(operationId: string, reason: string): Promise<boolean> {
    const mark: AgentAbandonmentMark = {
      at: new Date().toISOString(),
      phase: 'claimed',
      reason,
    };
    const [row] = await this.db
      .update(agentOperations)
      .set({
        completedAt: new Date(),
        completionReason: 'error',
        metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ abandonment: mark })}::jsonb`,
        status: 'error',
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          inArray(agentOperations.status, [
            'running',
            'waiting_for_human',
            'waiting_for_async_tool',
            'waiting_for_client',
          ]),
          this.ownership(),
        ),
      )
      .returning({ id: agentOperations.id });
    return Boolean(row);
  }

  /**
   * Retire the `claimed` mark once every abandonment side effect has landed, so
   * a later invocation cannot re-run hooks (or re-resume a parent) for a run
   * that was already finalised.
   */
  async markAbandonmentFinalized(operationId: string): Promise<void> {
    const mark: AgentAbandonmentMark = { phase: 'finalized' };
    await this.db
      .update(agentOperations)
      .set({
        metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ abandonment: mark })}::jsonb`,
      })
      .where(and(eq(agentOperations.id, operationId), this.ownership()));
  }

  /**
   * Keep the claim resumable while the parent-resume hand-off is still owed.
   *
   * The conversation side effects have landed by this point, but a sub-agent's
   * parent is only resumed by the *caller*, after `finalizeAbandoned` returns.
   * Retiring the mark here would make a crash in that window permanent: the
   * child reads as finalised, so no later invocation returns the linkage the
   * parent needs, and the parent stays parked in `waiting_for_async_tool`.
   * Persisting the linkage in the same UPDATE makes the hand-off itself
   * durable, so a retry replays exactly that step β€” and nothing else.
   */
  async markAbandonmentHandoffPending(
    operationId: string,
    handoff: Record<string, unknown>,
  ): Promise<void> {
    const mark: AgentAbandonmentMark = {
      at: new Date().toISOString(),
      handoff,
      phase: 'handoff_pending',
    };
    await this.db
      .update(agentOperations)
      .set({
        metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ abandonment: mark })}::jsonb`,
      })
      .where(and(eq(agentOperations.id, operationId), this.ownership()));
  }

  private async settleFrom(
    operationId: string,
    status: 'done' | 'error' | 'interrupted',
    fromStatuses: AgentOperationStatus[],
  ): Promise<boolean> {
    const [row] = await this.db
      .update(agentOperations)
      .set({
        completedAt: new Date(),
        completionReason: status === 'interrupted' ? 'interrupted' : status,
        status,
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          inArray(agentOperations.status, fromStatuses),
          this.ownership(),
        ),
      )
      .returning({ id: agentOperations.id });
    return Boolean(row);
  }

  /**
   * Record that ingest discarded a batch for this operation, first refusal wins.
   *
   * Deliberately NOT gated on `status = 'running'`: a terminal row is itself one
   * of the refusal reasons. The `?` guard keeps the first (and most informative)
   * refusal instead of letting the run's remaining batches overwrite it.
   */
  async recordHeteroIngestRejection(
    operationId: string,
    marker: HeteroIngestRejectionMarker,
  ): Promise<boolean> {
    const [row] = await this.db
      .update(agentOperations)
      .set({
        metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ heteroIngestRejection: marker })}::jsonb`,
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          this.ownership(),
          sql`NOT (coalesce(${agentOperations.metadata}, '{}'::jsonb) ? 'heteroIngestRejection')`,
        ),
      )
      .returning({ id: agentOperations.id });
    return Boolean(row);
  }

  /**
   * Shallow-merge top-level keys into the run's durable `metadata`, leaving
   * every other key intact. Not gated on status: diagnostic records may land on
   * a run that has already settled.
   */
  async mergeMetadata(operationId: string, patch: Record<string, unknown>): Promise<boolean> {
    const [row] = await this.db
      .update(agentOperations)
      .set({
        metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify(patch)}::jsonb`,
      })
      .where(and(eq(agentOperations.id, operationId), this.ownership()))
      .returning({ id: agentOperations.id });
    return Boolean(row);
  }

  /** Refresh the durable liveness lease while an operation owns an execution step. */
  async touchRunning(operationId: string): Promise<boolean> {
    const [row] = await this.db
      .update(agentOperations)
      .set({ updatedAt: new Date() })
      .where(
        and(
          eq(agentOperations.id, operationId),
          eq(agentOperations.status, 'running'),
          this.ownership(),
        ),
      )
      .returning({ id: agentOperations.id });

    return Boolean(row);
  }

  /**
   * Whether this operation is still running AND owns the given topic.
   *
   * The row β€” not `topic.metadata.runningOperation` β€” is the authority on
   * liveness: the marker is a best-effort rendering pointer that any client can
   * clear (a transport-level completion settles it while the producer keeps
   * going), whereas the row only leaves `running` through a terminal path.
   * Pairing it with `topicId` is what makes the answer safe to act on: it proves
   * the caller is about to write to the topic this operation actually belongs
   * to, not one it was handed.
   */
  async isRunningOnTopic(operationId: string, topicId: string): Promise<boolean> {
    const [row] = await this.db
      .select({ id: agentOperations.id })
      .from(agentOperations)
      .where(
        and(
          eq(agentOperations.id, operationId),
          eq(agentOperations.status, 'running'),
          eq(agentOperations.topicId, topicId),
          this.ownership(),
        ),
      )
      .limit(1);

    return Boolean(row);
  }

  /**
   * Fail a run whose dispatch was never confirmed: nothing has touched the row
   * since `dispatchedAt`. The first `heteroIngest` refreshes `updatedAt`, so a run
   * that did start wins the race and this returns false. Settles to `error` so the
   * caller's completion lifecycle persists onto the same status.
   */
  async settleUnconfirmedRunning(operationId: string, dispatchedAt: Date): Promise<boolean> {
    const [row] = await this.db
      .update(agentOperations)
      .set({ completedAt: new Date(), completionReason: 'error', status: 'error' })
      .where(
        and(
          eq(agentOperations.id, operationId),
          eq(agentOperations.status, 'running'),
          sql`${agentOperations.updatedAt} <= ${dispatchedAt}`,
          this.ownership(),
        ),
      )
      .returning({ id: agentOperations.id });

    return Boolean(row);
  }

  /**
   * Atomically retire an operation whose liveness lease has expired. A concurrent
   * heartbeat wins by moving updatedAt past staleBefore, preventing false recovery.
   */
  async settleStaleRunning(
    operationId: string,
    staleBefore: Date,
    latestTotalCost?: number,
  ): Promise<boolean> {
    const totalCost =
      latestTotalCost !== undefined && Number.isFinite(latestTotalCost)
        ? Math.max(0, latestTotalCost)
        : undefined;
    const [row] = await this.db
      .update(agentOperations)
      .set({
        completedAt: new Date(),
        completionReason: 'lease_expired',
        status: 'abandoned',
        ...(totalCost === undefined
          ? {}
          : {
              totalCost: sql`greatest(coalesce(${agentOperations.totalCost}, 0), ${totalCost})`,
            }),
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          eq(agentOperations.status, 'running'),
          sql`${agentOperations.updatedAt} < ${staleBefore}`,
          this.ownership(),
        ),
      )
      .returning({ id: agentOperations.id });

    return Boolean(row);
  }

  /**
   * Atomically claim the next redrive attempt for an operation whose liveness
   * lease has expired, so a stale step can be re-queued instead of stranding.
   *
   * The claim is the concurrency control for the whole reaper: the same
   * predicate that selects a candidate also consumes it, so two overlapping
   * sweeps (or two instances of one sweep) can never both re-queue the same
   * step. Three guards ride in the WHERE clause rather than in the caller:
   * - `status = 'running'` β€” a terminal op is nobody's business anymore.
   * - `updatedAt < staleBefore` β€” a heartbeat that landed between the SELECT
   *   and this UPDATE means the step is alive after all, and wins the race.
   * - attempt budget β€” a step that dies deterministically (poison payload,
   *   OOM) must stop costing LLM calls; when this predicate fails the caller
   *   falls back to abandoning the op with a user-visible error.
   *
   * Writing `metadata` also bumps `updatedAt` via `$onUpdate`, which re-arms
   * the lease: the redriven step gets a fresh stall window before the next
   * sweep can look at it again, and no extra bookkeeping is needed to keep
   * ticks from piling redrives onto an operation that is busy recovering.
   *
   * @returns the 1-based attempt number just claimed, or `null` when this
   *   operation is not (or no longer) eligible.
   */
  async claimStaleRedrive(
    operationId: string,
    staleBefore: Date,
    maxAttempts: number,
  ): Promise<number | null> {
    // `jsonb_build_object` and the bare comparison below both take `any`, so
    // every parameter feeding them needs an explicit cast β€” Postgres cannot
    // infer a placeholder's type from an `any` argument (42P18).
    const attempts = sql`coalesce((${agentOperations.metadata} #>> '{staleRedrive,attempts}')::int, 0)`;

    const [row] = await this.db
      .update(agentOperations)
      .set({
        metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || jsonb_build_object('staleRedrive', jsonb_build_object('attempts', ${attempts} + 1, 'lastAttemptAt', ${new Date().toISOString()}::text))`,
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          eq(agentOperations.status, 'running'),
          sql`${agentOperations.updatedAt} < ${staleBefore}`,
          sql`${attempts} < ${maxAttempts}::int`,
          this.ownership(),
        ),
      )
      .returning({ metadata: agentOperations.metadata });

    if (!row) return null;

    const claimed = (row.metadata as { staleRedrive?: { attempts?: number } } | null)?.staleRedrive
      ?.attempts;

    return typeof claimed === 'number' ? claimed : null;
  }

  /**
   * Give back an attempt claimed by {@link claimStaleRedrive} when the redrive
   * it was claimed for never actually went out.
   *
   * The budget exists to bound LLM spend on a step that dies deterministically,
   * so a delivery that failed to publish must not consume it β€” otherwise a
   * brief queue outage walks an otherwise healthy operation to its attempt
   * limit and retires it without a single recovery ever having been attempted.
   *
   * The claimed attempt number is checked in SQL so this can only ever undo
   * *its own* increment: a concurrent sweep that claimed the next attempt in
   * between moves the counter past `attempt` and this becomes a no-op.
   * `updatedAt` is deliberately left where the claim moved it, so the release
   * shortens no stall window β€” the next sweep still waits out a full lease.
   */
  async releaseStaleRedrive(operationId: string, attempt: number): Promise<boolean> {
    const [row] = await this.db
      .update(agentOperations)
      .set({
        metadata: sql`jsonb_set(coalesce(${agentOperations.metadata}, '{}'::jsonb), '{staleRedrive,attempts}', to_jsonb(${attempt - 1}::int))`,
      })
      .where(
        and(
          eq(agentOperations.id, operationId),
          sql`(${agentOperations.metadata} #>> '{staleRedrive,attempts}')::int = ${attempt}::int`,
          this.ownership(),
        ),
      )
      .returning({ id: agentOperations.id });

    return Boolean(row);
  }

  /**
   * Sum the terminal usage of every child operation forked from `parentOperationId`
   * (`callSubAgent` children, isolated group members).
   *
   * A read-time SUM rather than an accumulation on the parent row, because the
   * sub-agent completion bridge is contractually re-deliverable (QStash redelivery,
   * plus the watchdog abandon path synthesizing the same call) and its safety rests
   * on every side effect being overwrite-idempotent or CAS-guarded β€” an `x += child`
   * is neither, and would double-count on the second delivery. Re-deriving the sum is
   * exact no matter how many times it runs, and self-heals if a child row lands late.
   *
   * Children are already terminal by the time a parent completes: `persistCompletion`
   * writes the child's row *before* dispatching its `onComplete` hooks, and the bridge
   * that unparks the parent IS one of those hooks.
   */
  async sumChildUsage(parentOperationId: string): Promise<ChildUsageRollup> {
    const [row] = await this.db
      .select({
        llmCalls: sql<string | null>`sum(${agentOperations.llmCalls})`,
        toolCalls: sql<string | null>`sum(${agentOperations.toolCalls})`,
        totalCost: sql<string | null>`sum(${agentOperations.totalCost})`,
        totalInputTokens: sql<string | null>`sum(${agentOperations.totalInputTokens})`,
        totalOutputTokens: sql<string | null>`sum(${agentOperations.totalOutputTokens})`,
        totalTokens: sql<string | null>`sum(${agentOperations.totalTokens})`,
      })
      .from(agentOperations)
      .where(and(eq(agentOperations.parentOperationId, parentOperationId), this.ownership()));

    // `sum()` over zero rows is NULL, and numeric sums come back as strings.
    const num = (value: string | null | undefined): number => {
      const parsed = Number(value ?? 0);
      return Number.isFinite(parsed) ? parsed : 0;
    };

    return {
      llmCalls: num(row?.llmCalls),
      toolCalls: num(row?.toolCalls),
      totalCost: num(row?.totalCost),
      totalInputTokens: num(row?.totalInputTokens),
      totalOutputTokens: num(row?.totalOutputTokens),
      totalTokens: num(row?.totalTokens),
    };
  }

  /**
   * Raw ownership-scoped lookup. Agent-share visitor runs execute under the
   * CREATOR's identity, so this DOES return their operations β€” required by the
   * agent runtime (execution, intervention, completion, verify, abandon), which
   * resolves its current operation regardless of who started it. Creator-facing reads use
   * {@link AgentOperationModel.findOwnOperationById} instead.
   */
  async findById(operationId: string) {
    return findScopedOperation(this.db, this.ownership(), operationId);
  }

  /** All resumable operations in a proven topic, independent of its UI marker. */
  async findLiveByTopic(topicId: string) {
    return findLiveTopicOperations(this.db, this.ownership(), topicId);
  }

  /** Batch lookup for callers that would otherwise issue one query per id. */
  async findByIds(operationIds: string[]) {
    if (operationIds.length === 0) return [];
    return this.db
      .select()
      .from(agentOperations)
      .where(and(inArray(agentOperations.id, operationIds), this.ownership()));
  }

  /**
   * Creator-facing twin of {@link AgentOperationModel.findById}: excludes
   * operations recorded inside an agent-share visitor topic, so a creator
   * handed a raw visitor operation id gets nothing back instead of reading a
   * visitor conversation's trajectory (e.g. via a pre-signed trace URL).
   *
   * Mirrors `TopicModel.findById` / `TopicModel.findOwnTopicById`.
   */
  async findOwnOperationById(operationId: string) {
    const [row] = await this.db
      .select()
      .from(agentOperations)
      .where(
        and(
          eq(agentOperations.id, operationId),
          this.ownership(),
          notShareVisitorTopicRef(agentOperations.topicId),
        ),
      )
      .limit(1);
    return row ?? null;
  }

  /** Match a server-minted turn identity when a diagnostic dispatch receipt was lost. */
  async findByTopicSourceMessage(topicId: string, sourceMessageId: string) {
    const [operation] = await this.db
      .select()
      .from(agentOperations)
      .where(
        and(
          this.ownership(),
          eq(agentOperations.topicId, topicId),
          sql`${agentOperations.appContext}->>'sourceMessageId' = ${sourceMessageId}`,
        ),
      )
      .limit(1);
    return operation;
  }

  /**
   * Operations recorded for one topic, newest first β€” the lookup that turns a
   * topic id (what a user actually has on hand) into the operation ids their
   * traces are keyed by. `traceS3Key` rides along so callers can tell "no
   * snapshot was recorded" apart from "snapshot exists but the fetch failed".
   *
   * Creator-facing only (the trace panel). Agent-share visitor runs execute
   * under the CREATOR's identity, so their operation rows pass `ownership()`;
   * without the visitor guard a creator could read a visitor conversation's
   * full trajectory snapshot from a raw topic id.
   */
  async listByTopic(topicId: string, limit = 20) {
    return this.db
      .select({
        agentId: agentOperations.agentId,
        appContext: agentOperations.appContext,
        createdAt: agentOperations.createdAt,
        id: agentOperations.id,
        model: agentOperations.model,
        parentOperationId: agentOperations.parentOperationId,
        provider: agentOperations.provider,
        startedAt: agentOperations.startedAt,
        status: agentOperations.status,
        stepCount: agentOperations.stepCount,
        totalCost: agentOperations.totalCost,
        totalTokens: agentOperations.totalTokens,
        traceS3Key: agentOperations.traceS3Key,
        trigger: agentOperations.trigger,
      })
      .from(agentOperations)
      .where(
        and(
          eq(agentOperations.topicId, topicId),
          this.ownership(),
          notShareVisitorTopicRef(agentOperations.topicId),
        ),
      )
      .orderBy(sql`${agentOperations.createdAt} desc`)
      .limit(limit);
  }

  /**
   * Total USD cost of every operation bound to a task β€” the goal outer loop's
   * budget meter. Only root (task-bound) operations carry `taskId`, and each
   * root's `totalCost` scalar already includes its direct children's rollup
   * (see `persistCompletion`), so this sum covers verify / repair sub-runs
   * without walking parent chains. Re-derived on every call β€” exact regardless
   * of how many times a round settles.
   */
  async sumCostByTask(taskId: string): Promise<number> {
    const [row] = await this.db
      .select({ totalCost: sql<string | null>`sum(${agentOperations.totalCost})` })
      .from(agentOperations)
      .where(and(eq(agentOperations.taskId, taskId), this.ownership()));

    const parsed = Number(row?.totalCost ?? 0);
    return Number.isFinite(parsed) ? parsed : 0;
  }

  /**
   * Per-operation cost and token totals for a set of runs, keyed by operation.
   *
   * Feeds the goal round rail's audit hover: a round's block should be able to
   * say what it actually spent, and asking per round would be one query per
   * block. Each root's `totalCost` already rolls up its direct children, so no
   * parent-chain walk is needed here either.
   */
  async findUsageByOperations(
    operationIds: string[],
  ): Promise<Map<string, { cost: number; tokens: number }>> {
    const ids = [...new Set(operationIds.filter(Boolean))];
    if (ids.length === 0) return new Map();

    const rows = await this.db
      .select({
        id: agentOperations.id,
        totalCost: agentOperations.totalCost,
        totalTokens: agentOperations.totalTokens,
      })
      .from(agentOperations)
      .where(and(inArray(agentOperations.id, ids), this.ownership()));

    return new Map(
      rows.map((row) => [
        row.id,
        { cost: Number(row.totalCost ?? 0) || 0, tokens: Number(row.totalTokens ?? 0) || 0 },
      ]),
    );
  }

  /**
   * Load an operation together with its direct child operations (`callSubAgent`
   * children / isolated group members) β€” the (at most) two-layer operation
   * tree. File-Work registration gathers every op in this tree so a round's
   * tool calls, including those a sub-agent produced, are scanned together.
   * Owner-scoped. The root op (`id === operationId`) is included in the result.
   */
  async listOperationTree(operationId: string) {
    return this.db
      .select()
      .from(agentOperations)
      .where(
        and(
          this.ownership(),
          or(
            eq(agentOperations.id, operationId),
            eq(agentOperations.parentOperationId, operationId),
          ),
        ),
      );
  }

  /**
   * Longest single operation (agent run) wall-clock execution time over the last
   * year, in seconds. Wall clock (`completedAt - startedAt`) is the most faithful
   * "task duration" β€” it spans the whole run including tool calls and waiting,
   * not just LLM compute. Returns 0 when there are no completed operations.
   */
  async getMaxDurationSeconds(): Promise<number> {
    const startDate = today().subtract(1, 'year').startOf('day').toDate();

    const [row] = await this.db
      .select({
        seconds:
          sql<number>`COALESCE(MAX(EXTRACT(EPOCH FROM (${agentOperations.completedAt} - ${agentOperations.startedAt}))), 0)`.mapWith(
            Number,
          ),
      })
      .from(agentOperations)
      .where(
        and(
          this.ownership(),
          isNotNull(agentOperations.startedAt),
          isNotNull(agentOperations.completedAt),
          gte(agentOperations.createdAt, startDate),
        ),
      );

    return row?.seconds ?? 0;
  }

  /**
   * Atomically flip a parked parent op from `waiting_for_async_tool` back to
   * `running`. Returns true only for the single winner (affected === 1) so
   * concurrent sub-op completions that lose the race no-op instead of
   * double-resuming the parent.
   */
  async tryResumeFromAsyncTool(operationId: string): Promise<boolean> {
    const rows = await this.db
      .update(agentOperations)
      .set({ status: 'running' })
      .where(
        and(
          eq(agentOperations.id, operationId),
          eq(agentOperations.userId, this.userId),
          eq(agentOperations.status, 'waiting_for_async_tool'),
        ),
      )
      .returning({ id: agentOperations.id });
    return rows.length === 1;
  }

  /**
   * Atomically flip an op parked in `waiting_for_client` back to `running`.
   * True only for the single winner, so a manual "continue" racing an
   * automatic one resumes the run once.
   */
  async tryResumeFromClientWait(operationId: string): Promise<boolean> {
    const rows = await this.db
      .update(agentOperations)
      .set({ status: 'running' })
      .where(
        and(
          eq(agentOperations.id, operationId),
          this.ownership(),
          eq(agentOperations.status, 'waiting_for_client'),
        ),
      )
      .returning({ id: agentOperations.id });
    return rows.length === 1;
  }

  /**
   * Undo a won `tryResumeFromClientWait` whose resume step never got enqueued,
   * so the run stays parked (resumable, expirable, stoppable) instead of
   * sitting in `running` with nothing scheduled.
   */
  async revertClientWaitResume(operationId: string): Promise<boolean> {
    const rows = await this.db
      .update(agentOperations)
      .set({ status: 'waiting_for_client' })
      .where(
        and(
          eq(agentOperations.id, operationId),
          this.ownership(),
          eq(agentOperations.status, 'running'),
        ),
      )
      .returning({ id: agentOperations.id });
    return rows.length === 1;
  }

  /**
   * Retire an op still parked in `waiting_for_client` (its wait ran out or it
   * was stopped while waiting). Only matches the parked row, so a run a client
   * already resumed is never settled under it.
   */
  async settleClientWait(
    operationId: string,
    status: 'error' | 'interrupted' = 'error',
  ): Promise<boolean> {
    return this.settleFrom(operationId, status, ['waiting_for_client']);
  }

  /**
   * Operations of this user parked in `waiting_for_client`, newest first.
   * `providers` narrows to the ones the asking client can run before the
   * limit applies, so waits for another device's providers cannot crowd out
   * the ones it could take.
   */
  async listWaitingForClient(options: { limit?: number; providers?: string[] } = {}) {
    const { limit = 20, providers } = options;
    return this.db
      .select({
        id: agentOperations.id,
        provider: agentOperations.provider,
        topicId: agentOperations.topicId,
      })
      .from(agentOperations)
      .where(
        and(
          eq(agentOperations.status, 'waiting_for_client'),
          this.ownership(),
          providers ? inArray(agentOperations.provider, providers) : undefined,
        ),
      )
      .orderBy(desc(agentOperations.createdAt))
      .limit(limit);
  }

  // ============================================
  // Verify (delivery checker)
  // ============================================
  // The verify plan snapshot + rollup status moved off this table onto
  // `verify_runs` (the session entity), addressed via `VerifyRunModel`. The
  // `verify_plan` / `verify_status` columns here are deprecated (see schema) and
  // no longer read or written through this model.
}