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.

38.7 KB
Raw Blame
import type { ISnapshotStore } from '@lobechat/agent-tracing';
import { LOADING_FLAT } from '@lobechat/const';
import { ABANDONED_OPERATION_ERROR_PREFIX } from '@lobechat/const/goal';
import type { ChatMessageError } from '@lobechat/types';
import { AgentRuntimeErrorType, isAgentOperationSettled } from '@lobechat/types';
import debug from 'debug';
import { and, desc, eq, gt, gte, isNull, lte, ne, or, sql } from 'drizzle-orm';

import type { AgentAbandonmentMark } from '@/database/models/agentOperation';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { MessageModel } from '@/database/models/message';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { agentOperations, messages } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
// Direct file import (not the barrel) to avoid pulling in RuntimeExecutors and
// its workspace-package transitive deps in the unit-test environment.
import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';

import { CompletionLifecycle } from './CompletionLifecycle';
import { getServerHooks } from './hooks/serverHooks';
import type { SerializedHook } from './hooks/types';
import { OperationTraceRecorder } from './OperationTraceRecorder';
import { createDefaultSnapshotStore } from './snapshotStore';

const log = debug('lobe-server:abandon-operation');

/**
 * Report a failure that leaves terminal state unsettled.
 *
 * Everything on this path is best-effort, but some of it is not optional:
 * when the durable row, the run row or the terminal hook fails here, the run
 * ends with a row still claiming to be `running` and nothing left to report it
 * β€” a Task that never settles, a Goal that waits on it, and a user looking at a
 * spinner. Those failures get a real log line; the ones that only
 * cost a retry stay on `debug`.
 */
const reportSettleFailure = (message: string, context: unknown): void => {
  console.error(`[abandon-operation] ${message}: %O`, context);
};

interface AbandonOperationOptions {
  coordinator?: AgentRuntimeCoordinator;
  snapshotStore?: ISnapshotStore | null;
}

/**
 * Linkage for resuming the parent of an abandoned sub-agent. Surfaced so the
 * caller can run the `completeSubAgentBridge` β€” the watchdog-abandon path
 * otherwise skips the child's onComplete bridge and strands the parent in
 * `waiting_for_async_tool` forever (the orphaned-parent bug).
 */
export interface AbandonedSubAgentResume {
  /**
   * Why the child was abandoned. The bridge otherwise reloads the child's
   * coordinator state, which never received this error, and hands the parent a
   * bare "Sub-agent did not complete (error)." with no cause.
   */
  errorMessage: string;
  parentOperationId: string;
  /**
   * When true, the parent op is a shared-agent visitor run (its metadata
   * carries `streamOwnerUserId`). The inline resume path must construct
   * services with `includeShareVisitor: true` so the visitor-owned rows
   * remain visible.
   */
  streamOwnerUserId?: string;
  threadId: string;
  /** The parent's placeholder `role: 'tool'` message this run reports to. */
  toolMessageId: string;
  userId: string;
  workspaceId?: string;
}

export interface FinalizeAbandonedResult {
  /**
   * Whether this watchdog firing represents a real abandoned run. `found=false`
   * alone is ambiguous: normal runtime ops may already be cleaned up, while
   * device/hetero runs can have no coordinator state but still be stuck in DB.
   */
  abandoned?: boolean;
  /** Whether the assistant message was successfully marked as errored. */
  assistantMessageUpdated: boolean;
  /** Whether the operation was finalized into a snapshot (false if no partial existed). */
  finalized: boolean;
  /** Whether agent state was found in Redis. */
  found: boolean;
  /**
   * Set when the abandoned op was a sub-agent parked under a parent's
   * `callSubAgent`. The caller MUST bridge this to resume the parent.
   */
  subAgentResume?: AbandonedSubAgentResume;
}

/**
 * Reverse-trigger finalization for an operation whose Vercel function was
 * killed mid-flight. Invoked from a fresh function invocation (e.g. from the
 * agent-gateway DO inactivity watchdog) given just an `operationId`.
 *
 * Loads the agent state from Redis, marks it as errored, runs the same
 * `OperationTraceRecorder.finalize()` path the in-loop error handler would
 * have run, and updates the dangling assistant message in DB.
 *
 * Idempotent: calling twice is a no-op the second time because `finalize()`
 * removes the partial, so `loadAgentState` may return null or finalize will
 * skip due to missing partial. An operation whose durable row is already
 * settled is skipped outright, before any of that β€” see the guard in
 * `finalizeAbandoned`.
 */
/** Terminal status an abandonment wrote when it claimed the durable row. */
type ClaimedStatus = 'abandoned' | 'error';

/**
 * Read back the parent-resume linkage persisted with a `handoff_pending` mark.
 *
 * Validated field by field because it round-trips through jsonb: a truncated or
 * hand-edited mark must degrade to "nothing to resume" rather than construct a
 * bridge with `undefined` ids.
 */
const readAbandonmentHandoff = (
  mark: AgentAbandonmentMark | undefined,
): AbandonedSubAgentResume | undefined => {
  const resume = mark?.handoff?.resume;
  if (!resume || typeof resume !== 'object') return undefined;

  const candidate = resume as Partial<AbandonedSubAgentResume>;
  if (
    !candidate.parentOperationId ||
    !candidate.threadId ||
    !candidate.toolMessageId ||
    !candidate.userId
  ) {
    return undefined;
  }

  return candidate as AbandonedSubAgentResume;
};

export class AbandonOperationService {
  private readonly coordinator: AgentRuntimeCoordinator;
  private readonly snapshotStore: ISnapshotStore | null;
  private readonly traceRecorder: OperationTraceRecorder;

  constructor(
    private readonly db: LobeChatDatabase,
    options?: AbandonOperationOptions,
  ) {
    this.coordinator = options?.coordinator ?? new AgentRuntimeCoordinator();
    this.snapshotStore =
      options?.snapshotStore !== undefined ? options.snapshotStore : createDefaultSnapshotStore();
    this.traceRecorder = new OperationTraceRecorder(this.snapshotStore);
  }

  /**
   * @param options.settledAsAbandoned Set when the caller already retired the
   * durable row with its own compare-and-set (`settleStaleRunning`) and only
   * wants the side effects. The lifecycle then persists onto that status rather
   * than racing it, so `onComplete` / `onError` still fire.
   */
  async finalizeAbandoned(
    operationId: string,
    reason: string,
    options?: { settledAsAbandoned?: boolean },
  ): Promise<FinalizeAbandonedResult> {
    const result: FinalizeAbandonedResult = {
      assistantMessageUpdated: false,
      finalized: false,
      found: false,
    };

    // A caller that already CAS'd the row to a terminal status owns the
    // abandonment: its claim is the decision, and this call only runs the side
    // effects. `StaleOperationReaper` and the orphaned-run settle in `runStep`
    // both arrive this way.
    const callerClaimed = options?.settledAsAbandoned === true;

    // The durable row is the authority on whether anything is left to abandon.
    // The inactivity watchdog fires on *silence*, and a run that finished
    // normally is silent too once its terminal event fails to reach the gateway
    // β€” so this call can arrive for an operation that already settled. The
    // snapshot side cannot tell the two apart: a completed run can still leave a
    // partial behind, which is exactly the `found && finalized` shape the
    // gateway has to read as a real death. Trusting the row instead keeps a
    // phantom timeout from stamping a failure on a conversation that already
    // delivered its answer, and reports it as a phantom so the gateway can
    // reconcile rather than record one.
    const row = await this.findOperationRow(operationId);
    // A claim that never finished is not a settled run. `claimForAbandonment`
    // retires the row *before* the side effects that the conversation depends
    // on, so a host recycled in that window leaves a terminal row with nothing
    // written: no error bubble, no topic cleanup, no hooks, no parent resume β€”
    // and `StaleOperationReaper` only scans live rows, so nothing ever picks it
    // back up. The `claimed` mark is the difference between "someone else
    // settled this" and "we started and got cut off", so re-enter instead of
    // reporting a phantom.
    const abandonmentMark = (row?.metadata as { abandonment?: AgentAbandonmentMark } | undefined)
      ?.abandonment;
    const resumableClaim = abandonmentMark?.phase === 'claimed';
    // Every side effect already landed in the invocation that wrote
    // `handoff_pending`; the only thing still owed is the caller's parent-resume
    // hand-off. Replaying the full finalisation would fire the same
    // `onComplete` / `onError` hooks a second time, so hand back the persisted
    // linkage and let the caller retry just that step.
    if (row && !callerClaimed && abandonmentMark?.phase === 'handoff_pending') {
      result.abandoned = true;
      result.finalized = true;
      result.found = true;
      result.subAgentResume = readAbandonmentHandoff(abandonmentMark);
      log('[%s] abandonment hand-off replayed: parent resume still owed', operationId);
      return result;
    }
    if (row && !callerClaimed && !resumableClaim && isAgentOperationSettled(row.status)) {
      log('[%s] abandon skipped: operation already %s', operationId, row.status);
      result.abandoned = false;
      return result;
    }

    // That read is a fast path only β€” the run can still settle between it and
    // the side effects below (the executor commits `done` while the watchdog is
    // deciding), and the error written then is invisible to the `settleLive`
    // safety net at the end of this method, because that CAS runs after the
    // damage. So claim the live row first and let the claim be the decision: it
    // fails exactly when the run settled under us, and once it wins, this call
    // owns the transition under the same contract as a caller-claimed row.
    //
    // Which terminal status the claim wrote matters downstream: the lifecycle
    // persists onto it, and `recordCompletion` refuses to move a row from one
    // terminal status to another. A caller's `settleStaleRunning` wrote
    // `abandoned`; this local claim writes `error`, so the hooks must persist
    // `error` β€” reporting it as `abandoned` would be refused and silently drop
    // `onComplete` / `onError` for every real watchdog abandonment.
    let claimedStatus: ClaimedStatus | undefined = callerClaimed
      ? 'abandoned'
      : resumableClaim
        ? ((row?.status === 'abandoned' ? 'abandoned' : 'error') as ClaimedStatus)
        : undefined;
    if (row && !claimedStatus) {
      const claimed = await new AgentOperationModel(
        this.db,
        row.userId,
        row.workspaceId ?? undefined,
      ).claimForAbandonment(operationId, reason);
      if (!claimed) {
        log('[%s] abandon skipped: operation settled before it could be claimed', operationId);
        result.abandoned = false;
        return result;
      }
      claimedStatus = 'error';
    }

    const state = await this.coordinator.loadAgentState(operationId);
    if (!state) {
      log('[%s] no agent state in coordinator β€” already cleaned up', operationId);
      await this.finalizeRunningOperationWithoutState(operationId, reason, result, claimedStatus);
      // Only once the no-state side effects have landed: the mark is what a
      // retry reads to decide whether it still owes this run any work.
      await this.markAbandonmentFinalized(operationId, row, callerClaimed);
      return result;
    }
    result.found = true;

    const metadata = (state.metadata ?? {}) as {
      assistantMessageId?: string;
      /** Present only for shared-agent visitor runs (visitor owns the stream). */
      streamOwnerUserId?: string;
    };
    const origin = state.origin ?? {};
    const shouldDispatchAbandonedLifecycle =
      state.status === 'running' ||
      state.status === 'waiting_for_human' ||
      state.status === 'waiting_for_async_tool' ||
      state.status === 'waiting_for_client';
    const message = `${ABANDONED_OPERATION_ERROR_PREFIX} ${reason}`;
    const error: ChatMessageError = {
      body: { message },
      message,
      type: AgentRuntimeErrorType.AgentRuntimeError,
    };

    // Synthesize a failed-step record at index = lastCompleted + 1 so consumers
    // see the operation ended at a step that never produced data.
    const partial = this.snapshotStore
      ? await this.snapshotStore.loadPartial(operationId).catch(() => null)
      : null;
    const lastStepIndex = partial?.steps?.length
      ? Math.max(...partial.steps.map((s) => s.stepIndex))
      : -1;
    const failedStep = { startedAt: Date.now(), stepIndex: lastStepIndex + 1 };

    // Mutate state for finalize β€” recorder reads cost / tokens / metadata off this.
    const finalState = { ...state, error, status: 'error' as const };

    if (this.snapshotStore) {
      await this.traceRecorder.finalize(operationId, {
        completionReason: 'error',
        error: { message, type: String(error.type) },
        failedStep,
        state: finalState,
      });
      // finalize swallows its own errors via try/catch, so we treat reaching
      // this line as success. If the partial was missing we still mark the
      // assistant message β€” that's the more important user-visible signal.
      result.finalized = partial !== null;
    }

    // Shared-agent visitor runs mark themselves with `streamOwnerUserId` on
    // the operation metadata (the op executes as the creator `userId`, but the
    // visitor owns the stream). The visitor-owned rows are excluded from
    // MessageModel/TopicModel/CompletionLifecycle by default, so the cleanup
    // path must opt in when this flag is present.
    const includeShareVisitor = Boolean(metadata.streamOwnerUserId);

    if (origin.userId) {
      const messageModel = new MessageModel(this.db, origin.userId, origin.workspaceId, undefined, {
        includeShareVisitor,
      });

      try {
        if (metadata.assistantMessageId) {
          // The dying step got as far as creating its placeholder, so the
          // failure belongs on exactly that row.
          await messageModel.update(metadata.assistantMessageId, { error });
          result.assistantMessageUpdated = true;
        } else if (origin.topicId && !(await this.topicMovedOn(operationId, origin))) {
          // No placeholder: the step was killed before its first token, which
          // is the usual shape when the host is recycled mid-LLM-call. The
          // turn would otherwise carry no error anywhere, and the client keys
          // its failure banner and retry action off `message.error` β€” that
          // silence is exactly why an abandoned turn renders as frozen rather
          // than failed.
          //
          // A fresh assistant row rather than marking the conversation tail:
          // the tail here is either the user's own turn, whose renderer reads
          // `error` for nothing but the double-click-to-edit guard and so
          // would show the user nothing at all, or a *previous* assistant turn
          // that genuinely succeeded and must not be relabelled as failed.
          await messageModel.create({
            agentId: origin.agentId,
            content: '',
            error,
            parentId: await this.resolveTailMessageId(
              {
                threadId: origin.threadId,
                topicId: origin.topicId,
                userId: origin.userId,
                workspaceId: origin.workspaceId,
              },
              includeShareVisitor,
            ),
            model: state.modelRuntimeConfig?.model,
            provider: state.modelRuntimeConfig?.provider,
            role: 'assistant',
            threadId: origin.threadId ?? null,
            topicId: origin.topicId,
          });
          result.assistantMessageUpdated = true;
        }
      } catch (e) {
        reportSettleFailure(
          `abandoned op failed to mark its assistant message (op=${operationId})`,
          e,
        );
      }
    }

    if (origin.topicId && origin.userId) {
      try {
        const topicModel = new TopicModel(this.db, origin.userId, origin.workspaceId, undefined, {
          includeShareVisitor,
        });
        await topicModel.settleRunningOperation(origin.topicId, operationId);
      } catch (e) {
        reportSettleFailure(`abandoned op failed to settle its topic (op=${operationId})`, e);
      }
    }

    if (!origin.lineage?.isSubAgent && origin.userId && shouldDispatchAbandonedLifecycle) {
      try {
        await new CompletionLifecycle(this.db, origin.userId, origin.workspaceId, {
          includeShareVisitor,
        }).dispatchHooks(operationId, finalState, 'error', {
          settledAsAbandoned: claimedStatus === 'abandoned',
          skipErrorMessageWrite: result.assistantMessageUpdated,
          terminalClaimed: claimedStatus !== undefined,
        });
      } catch (e) {
        reportSettleFailure(
          `abandoned op failed to dispatch its terminal hooks (op=${operationId})`,
          e,
        );
      }
    }

    // Safety net for the durable row. `dispatchHooks` owns the rich terminal
    // write (step count, usage, cost, traceS3Key) via `persistCompletion`, but
    // it only runs behind the guard above: a sub-agent, a missing
    // `origin.userId`, or a state whose `status` is not one of
    // running/waiting_* (e.g. a step boundary persisted as `idle`) all skip it
    // silently, and a throw inside it is swallowed as non-fatal. Any of those
    // used to leave the operation `running` forever β€” nothing else retires a
    // non-Goal op, so it stayed live on the dashboard and blocked its own
    // recovery. `settleLive` is idempotent and only matches rows still live, so
    // it cannot overwrite the richer outcome when the dispatch did happen. It
    // also covers a parked row (`waiting_for_human` / `waiting_for_async_tool`):
    // a sub-agent child parked on its own nested call skips the dispatch above,
    // and once abandoned nothing can ever resume it.
    if (origin.userId) {
      try {
        const settled = await new AgentOperationModel(
          this.db,
          origin.userId,
          origin.workspaceId,
        ).settleLive(operationId, 'error');
        if (settled) {
          log('[%s] durable row settled by abandon safety net', operationId);
        }
      } catch (e) {
        reportSettleFailure(
          `abandon safety net could not retire the durable row (op=${operationId})`,
          e,
        );
      }
    }

    // Resolve sub-agent β†’ parent linkage. The watchdog killed this op without
    // firing its onComplete bridge, so a parent parked on `callSubAgent` would
    // otherwise wait on this slot forever. We surface the ids the caller needs
    // to backfill the placeholder tool message and CAS-resume the parent.
    // parentOperationId + threadId live on the (persistent) operation row;
    // toolMessageId is this run's own placeholder (`lineage.progressAnchor`),
    // falling back to the thread's sourceMessageId. The fallback alone is not
    // enough: a continued sub-agent (`callSubAgent({ subAgentId })`) reuses its
    // thread, whose sourceMessageId is the FIRST run's placeholder, while the
    // parent now waits on a new one. When this is set, the coordinator
    // cleanup below is SKIPPED so the durable resume can still resolve userId.
    //
    // Isolated group members ALSO run with `isSubAgent: true` and an isolation
    // thread, but their parent (supervisor) is resumed through the group K=N
    // bridge (`completeGroupActionMember`, driven by the member's own
    // `scheduleGroupMemberTimeout`) β€” routing them through the sub-agent bridge
    // would backfill the wrong message and never satisfy the group barrier. They
    // are tagged `orchestrationRole: 'member'`, so skip them here.
    if (
      origin.lineage?.isSubAgent &&
      origin.lineage?.orchestrationRole !== 'member' &&
      origin.userId
    ) {
      try {
        const opRow = await new AgentOperationModel(
          this.db,
          origin.userId,
          origin.workspaceId,
        ).findById(operationId);
        const parentOperationId = opRow?.parentOperationId ?? undefined;
        const threadId = opRow?.threadId ?? origin.threadId ?? undefined;
        if (parentOperationId && threadId) {
          const anchoredToolMessageId =
            origin.lineage?.progressAnchor?.parentOperationId === parentOperationId
              ? origin.lineage.progressAnchor.toolMessageId
              : undefined;
          const toolMessageId =
            anchoredToolMessageId ??
            (await new ThreadModel(this.db, origin.userId, origin.workspaceId).findById(threadId))
              ?.sourceMessageId ??
            undefined;
          if (toolMessageId) {
            result.subAgentResume = {
              errorMessage: message,
              parentOperationId,
              // Forward the visitor-run marker so an inline resume (local mode)
              // constructs its services with `includeShareVisitor: true`; the
              // queue-mode `subagent-callback` re-derives the same flag from
              // the parent op's coordinator metadata.
              streamOwnerUserId: metadata.streamOwnerUserId,
              threadId,
              toolMessageId,
              userId: origin.userId,
              workspaceId: origin.workspaceId,
            };
          } else {
            log('[%s] sub-agent abandon: thread %s has no sourceMessageId', operationId, threadId);
          }
        }
      } catch (e) {
        // Non-fatal: the parent still has the bounded async-tool verify watchdog
        // as a fallback. Log so a failed resume hand-off stays observable.
        log('[%s] sub-agent parent-resume linkage lookup failed: %O', operationId, e);
      }
    }

    // Skip coordinator cleanup when a parent resume is still pending. The
    // durable subagent-callback (queue mode) re-resolves THIS op's userId from
    // the coordinator metadata, so deleting it now would 401 every redelivery
    // and strand the parent. The lingering state expires on its own Redis TTL.
    if (!result.subAgentResume) {
      try {
        await this.coordinator.deleteAgentOperation(operationId);
      } catch (e) {
        log('[%s] coordinator cleanup failed (non-fatal): %O', operationId, e);
      }
    }

    // Close the claim only after every side effect above has run β€” hooks last,
    // so an interruption before this point still looks resumable, and one after
    // it can never fire them twice (nor re-resume the same parent).
    //
    // A pending parent resume is the exception: it happens in the *caller*,
    // after this method returns, and the process can die in that gap. Keeping
    // the mark resumable and carrying the linkage lets the retry replay the
    // hand-off; the caller retires the mark once the resume actually landed
    // (`completeAbandonmentHandoff`).
    if (result.subAgentResume) {
      await this.markAbandonmentHandoffPending(operationId, row, result.subAgentResume);
    } else {
      await this.markAbandonmentFinalized(operationId, row, callerClaimed);
    }

    log('[%s] abandoned op finalized (reason=%s): %O', operationId, reason, result);
    return result;
  }

  /**
   * Retire the `claimed` mark written by {@link AgentOperationModel.claimForAbandonment}.
   *
   * Skipped for caller-claimed rows: those were retired by another writer
   * (`settleStaleRunning`), never carried this mark, and are not re-enterable
   * anyway. A failure here is logged, not thrown β€” the abandonment itself
   * already landed, and the worst case is one redundant re-entry later.
   */
  private async markAbandonmentFinalized(
    operationId: string,
    row: { userId?: string | null; workspaceId?: string | null } | null | undefined,
    callerClaimed: boolean,
  ): Promise<void> {
    if (callerClaimed || !row?.userId) return;
    try {
      await new AgentOperationModel(
        this.db,
        row.userId,
        row.workspaceId ?? undefined,
      ).markAbandonmentFinalized(operationId);
    } catch (e) {
      log('[%s] abandonment finalize mark failed (non-fatal): %O', operationId, e);
    }
  }

  /**
   * Persist the parent-resume linkage and keep the claim resumable.
   *
   * Skipped for caller-claimed rows for the same reason as
   * {@link markAbandonmentFinalized}. A failure here is logged, not thrown: it
   * only costs a redundant replay, never the abandonment itself.
   */
  private async markAbandonmentHandoffPending(
    operationId: string,
    row: { userId?: string | null; workspaceId?: string | null } | null | undefined,
    resume: AbandonedSubAgentResume,
  ): Promise<void> {
    if (!row?.userId) return;
    try {
      await new AgentOperationModel(
        this.db,
        row.userId,
        row.workspaceId ?? undefined,
      ).markAbandonmentHandoffPending(operationId, { resume });
    } catch (e) {
      log('[%s] abandonment hand-off mark failed (non-fatal): %O', operationId, e);
    }
  }

  /**
   * Retire the abandonment claim once the caller's parent-resume hand-off has
   * landed, so a later invocation neither replays the hand-off nor re-fires the
   * hooks.
   *
   * Called by the endpoint right after `resumeAbandonedParent` returns. A
   * failure is swallowed: the mark stays `handoff_pending`, which is the safe
   * direction (one redundant replay) rather than the unsafe one (a stranded
   * parent).
   */
  async completeAbandonmentHandoff(operationId: string): Promise<void> {
    const row = await this.findOperationRow(operationId);
    await this.markAbandonmentFinalized(operationId, row, false);
  }

  private async finalizeRunningOperationWithoutState(
    operationId: string,
    reason: string,
    result: FinalizeAbandonedResult,
    claimedStatus?: ClaimedStatus,
  ): Promise<void> {
    const op = await this.findOperationRow(operationId);
    // A row this abandonment already claimed (`settleStaleRunning` writes
    // `abandoned`, the live-row claim above writes `error`) is terminal on
    // purpose, so it still needs the topic / placeholder / hook side effects
    // below β€” otherwise the row retires while the turn keeps loading.
    const preClaimed = claimedStatus !== undefined && op?.status === claimedStatus;
    // Only an `abandoned` pre-claim has to be persisted onto as-is: the local
    // `error` claim matches the status the terminal write below records anyway,
    // which `recordCompletion` accepts, so that write still fills in the error.
    const preClaimedAbandoned = preClaimed && claimedStatus === 'abandoned';
    if (
      !op ||
      (!preClaimed &&
        !['running', 'waiting_for_human', 'waiting_for_async_tool', 'waiting_for_client'].includes(
          op.status,
        ))
    ) {
      return;
    }

    result.abandoned = true;

    const message = `${ABANDONED_OPERATION_ERROR_PREFIX} ${reason}`;
    const error: ChatMessageError = {
      body: { message },
      message,
      type: AgentRuntimeErrorType.AgentRuntimeError,
    };

    // The `abandoned` pre-claim already wrote the terminal row; do not overwrite it.
    if (!preClaimedAbandoned) {
      try {
        await new AgentOperationModel(
          this.db,
          op.userId,
          op.workspaceId ?? undefined,
        ).recordCompletion(operationId, {
          completedAt: new Date(),
          completionReason: 'error',
          error: { message, type: String(error.type) },
          // A resumed claim may already carry the real counters β€”
          // `CompletionLifecycle` persists usage before the finalise mark
          // lands β€” so writing zeros here would erase the run's statistics.
          // On a fresh claim these are the row's current values (usually 0),
          // which is exactly what "no state was recorded" should look like.
          llmCalls: op.llmCalls ?? 0,
          processingTimeMs: op.startedAt ? Date.now() - new Date(op.startedAt).getTime() : null,
          status: 'error',
          stepCount: op.stepCount ?? 0,
          toolCalls: op.toolCalls ?? 0,
          totalTokens: op.totalTokens ?? 0,
        });
      } catch (e) {
        reportSettleFailure(
          `no-state abandon could not retire the durable row (op=${operationId})`,
          e,
        );
      }
    }

    const settled = await this.settleOperationTopic(op, operationId);
    if (settled.assistantMessageId) {
      try {
        // No-state cleanup path: this is a system-side finalize keyed on ids
        // read from the persisted `agentOperations` row (no user input), and the
        // op may belong to a shared-agent visitor conversation whose rows the
        // default MessageModel gate would hide. Opt in unconditionally so the
        // placeholder can still be marked errored when the coordinator state has
        // already evaporated.
        const messageModel = new MessageModel(
          this.db,
          op.userId,
          op.workspaceId ?? undefined,
          undefined,
          { includeShareVisitor: true },
        );
        await messageModel.update(settled.assistantMessageId, { content: '', error });
        result.assistantMessageUpdated = true;
      } catch (e) {
        log(
          '[%s] no-state abandon: assistant message update failed (non-fatal): %O',
          operationId,
          e,
        );
      }
    }

    // Heterogeneous and device runs never have coordinator state, so this is
    // the only terminal they get when the process dies silently. Their hooks
    // (task lifecycle, bot callbacks) must still hear about it β€” otherwise the
    // Task keeps a `running` topic forever and a Goal waits on it indefinitely.
    // A newer operation owning the topic means this callback cannot prove which
    // run the hooks belong to, the same rule `heteroFinish` applies.
    if (settled.ownershipUnproven) return;
    const serializedHooks = settled.hooks ?? readDurableHooks(op.metadata);
    if (
      !serializedHooks?.length &&
      !getServerHooks().some((hook) => hook.type === 'onComplete' || hook.type === 'onError')
    )
      return;

    try {
      await new CompletionLifecycle(this.db, op.userId, op.workspaceId ?? undefined, {
        includeShareVisitor: true,
      }).completeOperation(
        {
          agentId: op.agentId ?? undefined,
          assistantMessageId: settled.assistantMessageId,
          error,
          operationId,
          orchestrationRole: settled.orchestrationRole,
          serializedHooks,
          startedAt: op.startedAt ?? undefined,
          topicId: op.topicId ?? undefined,
          userId: op.userId,
        },
        'error',
        // Persist onto the pre-claimed `abandoned` row instead of being refused
        // as a conflicting terminal owner, which would skip the hooks. Either way
        // this abandonment already retired the row (its claim, or the write above),
        // so the lifecycle's write is the run's end, not a replay.
        preClaimedAbandoned
          ? { settledAsAbandoned: true, skipErrorMessageWrite: true, terminalClaimed: true }
          : { skipErrorMessageWrite: true, terminalClaimed: true },
      );
    } catch (e) {
      reportSettleFailure(
        `no-state abandon failed to dispatch its terminal hooks (op=${operationId})`,
        e,
      );
    }
  }

  /**
   * Anchor for an abandonment error when the dying step never created its own
   * assistant placeholder: the latest main-chain message of the run.
   *
   * Reuses the same spine query the runtime itself uses to pick a turn's
   * continuation point, so the error lands on the node the client is actually
   * rendering as the tail rather than on a tool child or a stale fork.
   */
  private async resolveTailMessageId(
    params: { threadId?: string | null; topicId: string; userId: string; workspaceId?: string },
    includeShareVisitor: boolean,
  ): Promise<string | undefined> {
    try {
      const messageModel = new MessageModel(this.db, params.userId, params.workspaceId, undefined, {
        includeShareVisitor,
      });
      return await messageModel.getLatestSpineMessageId({
        threadId: params.threadId ?? null,
        topicId: params.topicId,
      });
    } catch (e) {
      log('[%s] tail message lookup failed (non-fatal): %O', params.topicId, e);
      return undefined;
    }
  }

  /**
   * Whether a newer run has started on this conversation since the abandoned
   * one, which means the spine tail now belongs to that run, not to this one.
   *
   * The fallback failure row is anchored to the tail, so writing it after the
   * user has moved on would graft this run's error under the newer turn β€” and
   * an interactive start overwrites `runningOperation` rather than waiting, so
   * the topic marker alone cannot tell (a newer run that already finished has
   * cleared it too). The durable operation rows can: any top-level operation
   * on the same topic/thread created after this one. The abandoned run's own
   * sub-agent children are excluded, since they extend its turn.
   *
   * Fails closed: on a lookup error the row is not written, because a missing
   * error bubble is recoverable (the durable row still settles) and a failure
   * grafted onto the active branch is not.
   */
  private async topicMovedOn(
    operationId: string,
    origin: { threadId?: string; topicId?: string; userId?: string },
  ): Promise<boolean> {
    if (!origin.topicId || !origin.userId) return true;
    try {
      const newer = await (this.db as any).query?.agentOperations?.findFirst({
        columns: { id: true },
        where: and(
          eq(agentOperations.topicId, origin.topicId),
          eq(agentOperations.userId, origin.userId),
          origin.threadId
            ? eq(agentOperations.threadId, origin.threadId)
            : isNull(agentOperations.threadId),
          ne(agentOperations.id, operationId),
          or(
            isNull(agentOperations.parentOperationId),
            ne(agentOperations.parentOperationId, operationId),
          ),
          // Own alias on purpose: the relational query aliases the outer table,
          // and interpolated columns in the subquery would resolve against that
          // alias and compare each row with itself.
          gt(
            agentOperations.createdAt,
            sql`(select self.created_at from agent_operations self where self.id = ${operationId})`,
          ),
        ),
      });
      return Boolean(newer);
    } catch (e) {
      log('[%s] newer-run lookup failed, not writing a fallback row: %O', operationId, e);
      return true;
    }
  }

  private async findOperationRow(operationId: string) {
    try {
      return await (this.db as any).query?.agentOperations?.findFirst({
        where: eq(agentOperations.id, operationId),
      });
    } catch (e) {
      log('[%s] no-state abandon: operation lookup failed (non-fatal): %O', operationId, e);
      return null;
    }
  }

  private async settleOperationTopic(
    op: typeof agentOperations.$inferSelect,
    operationId: string,
  ): Promise<SettledOperationTopic> {
    let topicModel: TopicModel | undefined;

    if (op.topicId) {
      try {
        // No-state cleanup path: same rationale as the MessageModel above β€”
        // system-side finalize keyed on ids from the persisted operation row,
        // and the op may belong to a shared-agent visitor topic that the
        // default TopicModel gate would exclude. Opt in unconditionally.
        topicModel = new TopicModel(this.db, op.userId, op.workspaceId ?? undefined, undefined, {
          includeShareVisitor: true,
        });
        const settled = await topicModel.settleRunningOperation(op.topicId, operationId);
        if (settled.status === 'conflict') return { ownershipUnproven: true };
        if (settled.status !== 'settled') return {};
        const topicHooks = {
          hooks: settled.hooks as SerializedHook[] | undefined,
          orchestrationRole: settled.orchestrationRole,
        };
        if (settled.assistantMessageId) {
          return { ...topicHooks, assistantMessageId: settled.assistantMessageId };
        }
        return { ...topicHooks, ...(await this.findPlaceholderMessage(op, operationId)) };
      } catch (e) {
        // The topic could not be settled, so this run's hooks are suppressed β€”
        // which means the Task behind it never hears that it ended. Visible
        // even though the path continues.
        reportSettleFailure(
          `no-state abandon could not settle its topic, so the terminal hooks are suppressed (op=${operationId})`,
          e,
        );
        // A failed settle cannot rule out a newer operation on the topic, and
        // firing this run's task hook would then pause the replacement's Task.
        return { ...(await this.findPlaceholderMessage(op, operationId)), ownershipUnproven: true };
      }
    }

    return this.findPlaceholderMessage(op, operationId);
  }

  private async findPlaceholderMessage(
    op: typeof agentOperations.$inferSelect,
    operationId: string,
  ): Promise<{ assistantMessageId?: string }> {
    try {
      const startedAt = op.startedAt ? new Date(op.startedAt) : undefined;
      const lowerBound = startedAt ? new Date(startedAt.getTime() - 5000) : undefined;
      const upperBound = startedAt ? new Date(startedAt.getTime() + 5000) : undefined;
      const assistant = await (this.db as any).query?.messages?.findFirst({
        orderBy: [desc(messages.createdAt)],
        where: and(
          eq(messages.userId, op.userId),
          eq(messages.role, 'assistant'),
          op.topicId ? eq(messages.topicId, op.topicId) : undefined,
          op.agentId ? eq(messages.agentId, op.agentId) : undefined,
          op.provider ? eq(messages.provider, op.provider) : undefined,
          lowerBound ? gte(messages.createdAt, lowerBound) : undefined,
          upperBound ? lte(messages.createdAt, upperBound) : undefined,
          or(eq(messages.content, LOADING_FLAT), eq(messages.content, '')),
        ),
      });

      return { assistantMessageId: assistant?.id };
    } catch (e) {
      log('[%s] no-state abandon: assistant lookup failed (non-fatal): %O', operationId, e);
      return {};
    }
  }
}

interface SettledOperationTopic {
  assistantMessageId?: string;
  hooks?: SerializedHook[];
  orchestrationRole?: 'member' | 'supervisor';
  /**
   * The topic could not prove this run still owns it β€” a newer operation holds
   * it, or the settle itself failed β€” so this run's hooks must not fire.
   */
  ownershipUnproven?: boolean;
}

/** Queue-mode dispatch serializes the run's hooks onto the operation row. */
const readDurableHooks = (metadata: unknown): SerializedHook[] | undefined => {
  const hooks = (metadata as { _hooks?: unknown } | null | undefined)?._hooks;
  return Array.isArray(hooks) ? (hooks as SerializedHook[]) : undefined;
};