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.

13.1 KB
Raw Blame
import type { AgentRuntime, AgentRuntimeContext } from '@lobechat/agent-runtime';
import { getLlmCallCount } from '@lobechat/agent-runtime';
import debug from 'debug';

import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';

import { isSuccessLikeCompletionReason } from '../../CompletionLifecycle';
import { stepChangedCredentials } from '../../credentialFacts';
import { logToolCallPc } from '../../formalObservation';
import { buildStepPresentation, formatTokenCount } from '../../stepPresentation';
import type { DeferredMessagePatch } from '../../types';
import { INTERVENTION_LIFECYCLE_CHECKPOINT_KEY } from '../constants';
import type { AgentRuntimeServiceContext, InterventionLifecycleCheckpoint } from '../types';
import { publishStepMessagePatch, stepMessagesScopeKey } from './messagePatch';
import type { PreparedStepInput } from './prepare';

const log = debug('lobe-server:agent-runtime-service');

/** What this module reads off the service. */
export type StepRunStepDeps = Pick<
  AgentRuntimeServiceContext,
  | 'completionLifecycle'
  | 'coordinator'
  | 'determineCompletionReason'
  | 'parkForClientLlm'
  | 'publishSubAgentProgress'
  | 'queryUiMessages'
  | 'shouldContinueExecution'
  | 'streamManager'
>;

export type StepRunResult = Awaited<ReturnType<AgentRuntime['step']>>;
export type StepPresentation = ReturnType<typeof buildStepPresentation>['presentation'];

/**
 * Run the step (or take the forced finish), then reconcile it with a Stop that
 * landed meanwhile, or park the run for a client when no executor could make
 * its LLM call.
 */
export async function runAndReconcileStep(
  deps: StepRunStepDeps,
  {
    assertOwnership,
    currentContext,
    currentState,
    forcedFinishState,
    operationId,
    resumedClientLlmWait,
    runtime,
    stepIndex,
  }: PreparedStepInput & {
    /** Throws once this attempt no longer owns the operation; absent when commits are not fenced. */
    assertOwnership?: () => Promise<void>;
    operationId: string;
    runtime: AgentRuntime;
    stepIndex: number;
  },
): Promise<{ startAt: number; stepResult: StepRunResult }> {
  // Execute step (skipped when force-finishing a parked supervisor op).
  const startAt = Date.now();
  logToolCallPc(operationId, stepIndex, 'post.runtime_step_entered', () => ({
    forcedFinish: Boolean(forcedFinishState),
    stateStatus: currentState.status,
  }));
  let stepResult = forcedFinishState
    ? { events: [], newState: forcedFinishState, nextContext: undefined }
    : await runtime.step(currentState, currentContext);

  // The LLM call is where a step can outlive its lock. Check before anything
  // below writes on the step's behalf (the client park saves state).
  await assertOwnership?.();

  // Inner runtime.step() catches model-runtime exceptions and stuffs the
  // raw error into newState.error without re-throwing — so the outer
  // catch at the bottom of this method never sees them. Normalize +
  // classify here so the raw error doesn't reach Redis state, the
  // success-path trace finalize, or `persistCompletion`'s JSONB write.
  if (stepResult.newState.error) {
    stepResult.newState.error = formatErrorForState(stepResult.newState.error);
  }
  logToolCallPc(operationId, stepIndex, 'post.runtime_step_returned', () => ({
    errorCategory: stepResult.newState.error?.category ?? null,
    errorRetryable: stepResult.newState.error?.retryable ?? null,
    nextContextPresent: stepResult.nextContext !== undefined,
    stateStatus: stepResult.newState.status,
  }));

  // Check if the operation was interrupted while the step was executing
  // (e.g., user clicked abort during a long LLM call). Prefer the tiny
  // sentinel, then check the persisted status: some stops (share-run gate,
  // client LLM wait, intervention) persist `status: 'interrupted'` without
  // the sentinel. Only the status is read, not the whole state blob.
  const sentinelInterrupted = await deps.coordinator.isInterrupted(operationId);
  const wasInterrupted = sentinelInterrupted
    ? true
    : (await deps.coordinator.loadAgentStatus(operationId)) === 'interrupted';
  logToolCallPc(operationId, stepIndex, 'post.latest_state_loaded', () => ({
    interrupted: wasInterrupted,
  }));
  if (wasInterrupted) {
    // Stop can be persisted after a client-tool executor's last local
    // signal check but before this reconciliation read. If that executor
    // just returned a parked state, run the agent's existing abort path
    // once so every pending tool call gets a terminal row before the
    // interrupted state is saved.
    if (
      stepResult.newState.status === 'waiting_for_async_tool' &&
      stepResult.newState.pendingToolsCalling?.length &&
      currentContext
    ) {
      const interruptedState = structuredClone(stepResult.newState);
      interruptedState.status = 'interrupted';
      const abortContext: AgentRuntimeContext = {
        ...currentContext,
        payload: {
          ...(currentContext.payload as Record<string, unknown>),
          hasToolsCalling: true,
          toolsCalling: interruptedState.pendingToolsCalling,
        },
        phase: 'llm_result',
      };
      const abortResult = await runtime.step(interruptedState, abortContext);
      stepResult = {
        ...abortResult,
        events: [...stepResult.events, ...abortResult.events],
      };
    }

    stepResult.newState.status = 'interrupted';
    stepResult.newState.lastModified = new Date().toISOString();
    log('[%s][%d] Operation was interrupted during step execution', operationId, stepIndex);
  } else if (stepResult.newState.status === 'error') {
    // No client could run the step's LLM call: park for one instead of
    // failing (U4c). The parked state is what the step started from, so
    // a resume replays the same call.
    const parkedState = await deps.parkForClientLlm(
      operationId,
      stepResult.newState,
      currentContext,
      resumedClientLlmWait?.expiresAt,
      currentState,
    );
    if (parkedState) {
      stepResult = { ...stepResult, newState: parkedState, nextContext: undefined };
    }
  }

  return { startAt, stepResult };
}

/**
 * Persist the step: file Works and the intervention checkpoint before a
 * terminal save, the gateway message patch, the step result itself, and the
 * `step_complete` event. Returns whether the run continues and the step's
 * presentation.
 */
export async function saveAndPublishStep(
  deps: StepRunStepDeps,
  {
    assertOwnership,
    deferMessagePatch,
    gatewayMessagePatchEnabled,
    operationId,
    startAt,
    stepIndex,
    stepResult,
    stepStartUiMessages,
  }: {
    /** Throws once this attempt no longer owns the operation; absent when commits are not fenced. */
    assertOwnership?: () => Promise<void>;
    /**
     * The next step may run in this invocation, so a continuing step leaves its
     * message patch to that step's entry read instead of reading the topic.
     */
    deferMessagePatch: boolean;
    gatewayMessagePatchEnabled: boolean;
    operationId: string;
    startAt: number;
    stepIndex: number;
    stepResult: StepRunResult;
    stepStartUiMessages: Awaited<
      ReturnType<AgentRuntimeServiceContext['queryStepEntryMessages']>
    >['uiMessages'];
  },
): Promise<{
  content: StepPresentation['content'];
  /** This step's patch, left unpublished; set only when `deferMessagePatch` applied. */
  deferredMessagePatch?: DeferredMessagePatch;
  shouldContinue: boolean;
  stepPresentationData: StepPresentation;
  toolsCalling: StepPresentation['toolsCalling'];
}> {
  // Decide whether to schedule next step (hoisted above the save: it also
  // gates the pre-snapshot file-Work registration below)
  const shouldContinue = deps.shouldContinueExecution(stepResult.newState, stepResult.nextContext);

  // Register entity-file Works BEFORE the terminal save: `saveStepResult`
  // publishes `agent_runtime_end`, whose `uiMessages` snapshot the client
  // adopts as the settled message list — the Work rows must exist by then
  // or the file-Work card stays absent until a manual refresh. Perceived
  // loading is not extended: for runs with entity edits the early
  // `visible_output_end` is suppressed (see `createAgentRuntime`), so
  // loading covers this export window by design. Idempotent — the
  // dispatchHooks backstop below no-ops via the state marker.
  if (!shouldContinue) {
    const preSaveReason = deps.determineCompletionReason(stepResult.newState);
    if (preSaveReason === 'waiting_for_human') {
      stepResult.newState.metadata = {
        ...stepResult.newState.metadata,
        [INTERVENTION_LIFECYCLE_CHECKPOINT_KEY]: {
          state: 'pending',
          stepIndex,
        } satisfies InterventionLifecycleCheckpoint,
      };
    }

    // Success-like reasons ONLY — a `waiting_for_human` park must NOT
    // register because it is not a completed deliverable boundary. The
    // fresh approval continuation sees the complete authoritative
    // history and performs the terminal scan after the decision runs;
    // registering here would freeze pre-approval content too early.
    if (isSuccessLikeCompletionReason(preSaveReason)) {
      await deps.completionLifecycle.registerFileWorks(operationId, stepResult.newState);
      logToolCallPc(operationId, stepIndex, 'post.file_works_registered', () => ({}));
    }
  }

  // Protocol v2 native runs reconcile only what this step changed. The
  // full before/after lists stay server-side; the wire sees a bounded
  // patch. Publish before saveStepResult because a terminal save emits
  // agent_runtime_end immediately, and the client must apply the patch
  // before completing the run.
  //
  // A step that continues in this invocation skips that read: the next step
  // reads the topic at its entry anyway, a moment later, and its read becomes
  // this patch's "after" side. It is the fresher of the two, so anything
  // written in between reaches the client too.
  let deferredMessagePatch: DeferredMessagePatch | undefined;
  if (gatewayMessagePatchEnabled && stepStartUiMessages) {
    if (shouldContinue && deferMessagePatch) {
      deferredMessagePatch = {
        before: stepStartUiMessages,
        scopeKey: stepMessagesScopeKey(stepResult.newState),
        state: stepResult.newState,
        stepIndex,
      };
    } else {
      // Without group members, like the entry read it is diffed against.
      const settledUiMessages = await deps.queryUiMessages(stepResult.newState, {
        skipCompressedMembers: true,
        skipWorks: shouldContinue,
      });
      if (settledUiMessages) {
        await publishStepMessagePatch(deps, {
          after: settledUiMessages,
          before: stepStartUiMessages,
          operationId,
          state: stepResult.newState,
          stepIndex,
        });
      }
    }
  }

  // A credential the run just saved or connected changes the list the next
  // step must show, so the snapshot frozen at creation no longer holds.
  // Dropped before the save below — that write is what the next step
  // reloads, and nothing else persists the state on a plain step.
  if (stepChangedCredentials(stepResult.nextContext) && stepResult.newState.operationCredentials) {
    stepResult.newState.operationCredentials = undefined;
    log('[%s][%d] Credentials changed in-run; dropped the snapshot', operationId, stepIndex);
  }

  // Save state, coordinator will handle event sending automatically. This is
  // the commit: a redelivery of this step is skipped as already done once it
  // lands, so only the lock owner may write it.
  await assertOwnership?.();
  await deps.coordinator.saveStepResult(operationId, {
    ...stepResult,
    executionTime: Date.now() - startAt,
    stepIndex, // placeholder
  });
  logToolCallPc(operationId, stepIndex, 'post.step_result_saved', () => ({
    stateStatus: stepResult.newState.status,
    stateStepCount: stepResult.newState.stepCount,
  }));

  // The next step is scheduled after this event, so it always reports `false`.
  const nextStepScheduled = false;

  // Publish step complete event
  await deps.streamManager.publishStreamEvent(operationId, {
    data: {
      ...(stepResult.newState.host?.includeFinalState === true && {
        finalState: stepResult.newState,
      }),
      llmCalls: getLlmCallCount(stepResult.newState),
      nextStepScheduled,
      stepIndex,
    },
    stepIndex,
    type: 'step_complete',
  });
  logToolCallPc(operationId, stepIndex, 'post.step_complete_published', () => ({}));

  await deps.publishSubAgentProgress(stepResult.newState, stepIndex);

  // Build enhanced step completion log & presentation data
  const { presentation: stepPresentationData, summary: stepSummary } = buildStepPresentation(
    stepResult,
    Date.now() - startAt,
  );

  const { usage } = stepResult.newState;
  log(
    '[%s][%d] completed %s | total: %s tokens / $%s | llm×%d | tools×%d',
    operationId,
    stepIndex,
    stepSummary,
    formatTokenCount(stepPresentationData.totalTokens),
    stepPresentationData.totalCost.toFixed(4),
    usage?.llm?.apiCalls ?? 0,
    usage?.tools?.totalCalls ?? 0,
  );

  const toolsCalling = stepPresentationData.toolsCalling;
  const content = stepPresentationData.content;

  return { content, deferredMessagePatch, shouldContinue, stepPresentationData, toolsCalling };
}