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.

22.8 KB
Raw Blame
import type { ExecAgentResult } from '@lobechat/types';
import debug from 'debug';

import type { MessageModel } from '@/database/models/message';
import type { TopicModel } from '@/database/models/topic';
import { signUserJWT } from '@/libs/trpc/utils/internalJwt';
import type { AgentRuntimeService } from '@/server/services/agentRuntime';
import { isAbortError } from '@/server/services/agentRuntime/abort';

import type { ExecRunContext, InternalExecAgentParams } from '../types';
import type { ApprovalClaimState } from './approvalResume';
import type { OperationInitRequest } from './operationInit';
import { buildPendingInitSlots, resolveOperationInitSlots } from './operationInitSlots';
import type { OperationPrepResult } from './operationPrep';
import { traceStartStage } from './sendTracing';
import type { ToolDiscoveryResult } from './toolDiscovery';

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

export interface StartOperationDeps {
  agentRuntimeService: AgentRuntimeService;
  messageModel: MessageModel;
  retirePendingApprovalOperation: (operationId: string) => Promise<void>;
  topicModel: TopicModel;
  userId: string;
  withholdGatewayToken: boolean;
  workspaceId?: string;
}

/** What the init produced, or the request the step-0 worker will run it from. */
export type StartOperationInit =
  | {
      discovery: ToolDiscoveryResult;
      /** Final runtime context β€” base prep context with 16b/16c overrides applied. */
      initialContext: OperationPrepResult['initialContext'];
      prep: OperationPrepResult;
    }
  | { pendingRequest: OperationInitRequest };

export interface StartOperationInput {
  acceptsArtboardWorks?: boolean;
  /** See {@link InternalExecAgentParams.acceptsFileWorks}. */
  acceptsFileWorks?: boolean;
  /** See {@link InternalExecAgentParams.acceptsMemberRuntimeEnd}. */
  acceptsMemberRuntimeEnd?: boolean;
  approvalClaim: ApprovalClaimState;
  approvalSourceOperationId?: string;
  approvalSourceToolMessageIds: string[];
  /** Library skills the agent set to `auto`, kept on the world slot for the skill pool. */
  autoSkillIds?: string[];
  autoStart: boolean;
  botContext?: InternalExecAgentParams['botContext'];
  botPlatformContext?: InternalExecAgentParams['botPlatformContext'];
  clientIp?: string;
  /** Wire protocol the calling client declared; `2` opts the run into message_patch delivery. */
  clientProtocol?: 1 | 2;
  /** Tri-state disabled plugin identifiers, kept on the world slot for the context rules. */
  disabledPluginIds?: string[];
  discordContext?: any;
  enableExpertise: boolean;
  evalContext?: InternalExecAgentParams['evalContext'];
  evalRuntime?: InternalExecAgentParams['evalRuntime'];
  hooks?: InternalExecAgentParams['hooks'];
  includeFinalState?: boolean;
  init: StartOperationInit;
  initialLlmCalls?: number;
  initialStepCount?: number;
  /** Relay executor the calling client declared; lands on `state.host.llmExecutor`. */
  llmExecutor?: InternalExecAgentParams['llmExecutor'];
  /** See InternalExecAgentParams.markTopicRunning. */
  markTopicRunning?: boolean;
  maxSteps?: number;
  onOperationCreated?: InternalExecAgentParams['onOperationCreated'];
  /**
   * Called once the first step is queued. A later startup failure (a marker
   * write) still returns `success: false` while the run executes, so ownership
   * that follows the run (its concurrency slot) must transfer here.
   */
  onScheduled?: () => void;
  operationId: string;
  operationTaskId?: string;
  parentOperationId?: string;
  providedApprovalResolutionRequestId?: string;
  queueRetries?: number;
  queueRetryDelay?: string;
  /** See {@link InternalExecAgentParams.reservedOperationId}. */
  reservedOperation?: boolean;
  signal?: AbortSignal;
  stream?: boolean;
  topicStartOwnerOperationId?: string;
  updateAbortedAssistantMessage: (errorMessage: string) => Promise<void>;
  userAgent?: string;
  userInterventionConfig: InternalExecAgentParams['userInterventionConfig'];
  userTimezone?: string;
}

/**
 * Stage 19 of {@link AiAgentService.execAgent}: create the operation via
 * AgentRuntimeService, retire a legacy parked approval operation, persist the
 * topic's `runningOperation` reconnect marker, and mint the gateway token.
 *
 * Wrapped in try-catch to handle operation startup failures (e.g., QStash
 * unavailable): the persisted user/assistant rows stay valid, the assistant
 * bubble receives the startup error, and the caller gets `success: false`.
 */
export const startOperation = async (
  deps: StartOperationDeps,
  ctx: ExecRunContext,
  input: StartOperationInput,
): Promise<ExecAgentResult> => {
  const {
    agentConfig,
    appContext,
    assistantMessageId,
    canUseDevice,
    deviceAccessReason,
    model,
    parentMessageId,
    provider,
    resolvedAgentId,
    shareGate,
    topicEditingGroupId,
    topicId,
    trigger,
    userMessageId,
  } = ctx;
  const {
    acceptsArtboardWorks,
    acceptsFileWorks,
    acceptsMemberRuntimeEnd,
    approvalClaim,
    approvalSourceOperationId,
    approvalSourceToolMessageIds,
    autoSkillIds,
    autoStart,
    botContext,
    botPlatformContext,
    clientIp,
    disabledPluginIds,
    discordContext,
    enableExpertise,
    evalContext,
    evalRuntime,
    hooks,
    init,
    initialLlmCalls,
    initialStepCount,
    maxSteps,
    operationId,
    operationTaskId,
    parentOperationId,
    providedApprovalResolutionRequestId,
    queueRetries,
    queueRetryDelay,
    reservedOperation,
    signal,
    stream,
    topicStartOwnerOperationId,
    updateAbortedAssistantMessage,
    userAgent,
    userInterventionConfig,
    userTimezone,
  } = input;
  const ownsRootTopic =
    !appContext?.isolationThread && !appContext?.threadId && !topicStartOwnerOperationId;
  const markTopicRunning = input.markTopicRunning === true && autoStart && ownsRootTopic;
  const onOperationCreated = markTopicRunning
    ? async (createdOperationId: string) => {
        const updated = await deps.topicModel.updateMetadata(
          topicId,
          {
            runningOperation: {
              assistantMessageId,
              heteroType: null,
              operationId: createdOperationId,
              scope: appContext?.scope ?? undefined,
              startedAt: new Date().toISOString(),
            },
          },
          { status: 'running' },
        );
        if (!updated.length) throw new Error('Topic no longer available for this operation');
        await input.onOperationCreated?.(createdOperationId);
      }
    : input.onOperationCreated;
  // A builder topic continued from another surface (scope `main`, an approval
  // resume) arrives without the group it edits; the group the topic was opened
  // on stands in, so the run still knows its target.
  const editingGroupId =
    (appContext?.scope === 'group_agent_builder' ? appContext.editingGroupId : undefined) ||
    topicEditingGroupId;

  const pendingInitRequest = 'pendingRequest' in init ? init.pendingRequest : undefined;
  log('execAgent: creating operation %s (deferred init: %s)', operationId, !!pendingInitRequest);

  // Wrap in try-catch to handle operation startup failures (e.g., QStash unavailable)
  // If createOperation fails, we still have valid messages that need error info
  try {
    // A server-internal approval continuation (no client of its own declared
    // anything β€” client-facing routes always pass a boolean) streams to the
    // parked operation's client: carry its `member_runtime_end` declaration over
    // (read here, before the parked operation is retired below).
    const memberRuntimeEndAccepted =
      acceptsMemberRuntimeEnd ??
      (approvalSourceOperationId
        ? await deps.agentRuntimeService.acceptsMemberRuntimeEnd(approvalSourceOperationId)
        : undefined);
    // Same client, same device: the continuation also keeps the parked
    // operation's relay executor, or its next device-only call has none.
    const llmExecutor =
      input.llmExecutor ??
      (approvalSourceOperationId
        ? await deps.agentRuntimeService.getLlmExecutor(approvalSourceOperationId)
        : undefined);
    // Its `file_works` declaration too, or the continuation's terminal push
    // would drop the file Work card the parked client can render.
    const artboardWorksAccepted =
      acceptsArtboardWorks ??
      (approvalSourceOperationId
        ? await deps.agentRuntimeService.acceptsArtboardWorks(approvalSourceOperationId)
        : undefined);
    const fileWorksAccepted =
      acceptsFileWorks ??
      (approvalSourceOperationId
        ? await deps.agentRuntimeService.acceptsFileWorks(approvalSourceOperationId)
        : undefined);
    // The Group Agent Builder target is server state captured on the parked
    // operation row. A continuation is the SAME builder conversation: it must
    // re-bind to the edited group instead of relying on the resumed topic's
    // `metadata.editingGroupId`, which older topics never received β€” the member
    // tools would then answer `No active group found`. Never trusted from the
    // resolving client; read back from the durable row.
    const inheritedEditingGroupId = approvalSourceOperationId
      ? await deps.agentRuntimeService.getOperationEditingGroupId(approvalSourceOperationId)
      : undefined;
    const { modelCapabilities, ...initSlots } =
      'pendingRequest' in init
        ? buildPendingInitSlots({
            assistantMessageId,
            operationId,
            parentMessageId: userMessageId ?? parentMessageId ?? '',
          })
        : await resolveOperationInitSlots(init);
    const result = await deps.agentRuntimeService.createOperation({
      ...initSlots,
      acceptsArtboardWorks: artboardWorksAccepted,
      pendingInitRequest,
      acceptsFileWorks: fileWorksAccepted,
      acceptsMemberRuntimeEnd: memberRuntimeEndAccepted,
      clientProtocol: input.clientProtocol,
      includeFinalState: input.includeFinalState,
      llmExecutor,
      agentConfig,
      agentShareVisitor: shareGate
        ? {
            agentId: shareGate.agentId,
            // Mirrors `shareConfig.allowReadMemory` so `BuiltinToolsExecutor`
            // can re-check the memory tool's grant at dispatch time (the
            // actual chokepoint) via `isShareBlockedDataToolCall` β€” see
            // `shareGate/dispatch.ts`.
            allowReadMemory: shareGate.shareConfig.allowReadMemory,
            // Re-applied at dispatch by the device-builtin and device-only MCP
            // gates, so they decide exactly as the assembled tool set did.
            canUseDevice: shareGate.canUseDevice,
            // Mirrors `shareConfig.toolGrants` so tool runtimes resolved
            // outside `toolManifestMap` (e.g. `activateSkill`, which queries
            // builtin/DB skills by name) can enforce the same allowlist.
            toolGrants: shareGate.shareConfig.toolGrants,
            // Sourced from the agent's OWN persisted assignment
            // (`agentConfig.knowledgeBases`, already blanked by
            // `applyShareGateToAgentConfig` in `execAgent`), never from visitor
            // input. Lets `isShareBlockedDataToolCall` scope
            // `lobe-knowledge-base.viewKnowledgeBase`'s `id` argument to
            // knowledge bases actually mounted on this agent.
            knowledgeBaseIds: (agentConfig.knowledgeBases ?? [])
              .filter((kb: { enabled?: boolean | null; id?: string | null }) => kb.enabled && kb.id)
              .map((kb: { id?: string | null }) => kb.id as string),
            // The share instance this run was authorized against. Re-read (not
            // reused) at every step boundary by
            // `AgentRuntimeService.executeStep` via
            // `AgentShareModel.isRunStillAuthorized`, so a revocation
            // committed mid-run is caught at the next step instead of only at
            // creation time. See `AgentShareGate.shareId`'s JSDoc for why the
            // id itself is the revocation token.
            shareId: shareGate.shareId,
            // Mirrors `shareConfig.skillGrants` so the skill runtime can
            // re-check every load against the SAME allowlist the skill pool was
            // assembled from. Assembly alone is not enough: `activateSkill`
            // resolves a model-supplied skill NAME, so a name the pool never
            // offered still reaches the runtime.
            skillGrants: shareGate.shareConfig.skillGrants,
            visitorUserId: shareGate.visitorUserId,
          }
        : undefined,
      autoSkillIds,
      disabledPluginIds,
      userTimezone,
      appContext: {
        // Background self-iteration runs execute under a builtin slug (so they
        // inherit the builtin agent's tools / systemRole / model), but their
        // resource tools and receipts must attribute to the *reviewed* user
        // agent, which rides on the marker. Prefer it so the tool-execution
        // context (state.origin.agentId) targets the reviewed agent; ordinary
        // runs (no marker) fall back to the resolved executing agent.
        agentId: appContext?.agentSignal?.agentId ?? resolvedAgentId,
        assistantMessageId,
        // Propagate the originating request's client IP / user agent into
        // state.metadata (via the `...appContext` spread in createOperation) so
        // downstream LLM-call metadata can carry them for auditing and spend
        // attribution.
        clientIp,
        userAgent,
        // When scope === 'agent_builder', agentId stays as the builder builtin so
        // message ownership and queryUiMessages remain correct. editingAgentId
        // carries the actual editing target separately; only the AgentBuilder server
        // runtime reads it, keeping the rest of the pipeline unaffected.
        ...(appContext?.scope === 'agent_builder' && appContext?.editingAgentId
          ? { editingAgentId: appContext.editingAgentId }
          : {}),
        // Mirror of the above for the Group Agent Builder panel: the run is
        // owned by the builtin builder agent, so the edited group only rides
        // here. Read by the group-agent-builder server runtime and by the
        // `<current_group_context>` injector.
        //
        // An intervention continuation arrives without the group (the parked
        // run's client is gone), so the parked operation's durable target
        // stands in β€” the same inheritance `fileWorks` / `memberRuntimeEnd`
        // already use. An explicit request value always wins.
        ...(editingGroupId || inheritedEditingGroupId
          ? { editingGroupId: editingGroupId ?? inheritedEditingGroupId }
          : {}),
        // Run-scoped Agent Signal marker for background self-iteration / memory
        // runs β€” lands in state.origin.signal so the completion path can
        // project receipts/briefs. Undefined for ordinary chat runs.
        ...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),
        defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,
        documentId: appContext?.documentId,
        groupId: appContext?.groupId,
        isSubAgent: appContext?.isSubAgent,
        // Persist the orchestration role on state.metadata so the
        // inactivity-watchdog abandon path can distinguish an isolated group
        // member ('member') from a genuine callSubAgent child.
        orchestrationRole: appContext?.orchestrationRole,
        projectId: appContext?.projectId,
        scope: appContext?.scope,
        sessionId: appContext?.sessionId,
        sourceMessageId: userMessageId ?? parentMessageId ?? undefined,
        // Live-progress anchor for a callSubAgent child β€” carries the parked
        // parent's operationId + placeholder tool message so the child's step
        // loop can stream its running totals down the parent's gateway channel.
        subAgentProgress: appContext?.subAgentProgress,
        taskId: operationTaskId,
        threadId: appContext?.threadId,
        topicId,
        trigger,
      },
      autoStart,
      onOperationCreated,
      botContext,
      botPlatformContext,
      deviceAccessPolicy: { canUseDevice, reason: deviceAccessReason },
      discordContext,
      evalContext,
      evalRuntime,
      enableExpertise,
      initialLlmCalls,
      initialStepCount,
      ...(providedApprovalResolutionRequestId && approvalSourceOperationId
        ? {
            interventionResolution: {
              resolutionRequestId: providedApprovalResolutionRequestId,
              sourceOperationId: approvalSourceOperationId,
              sourceToolMessageIds: [...approvalSourceToolMessageIds].sort(),
            },
          }
        : {}),
      ...(providedApprovalResolutionRequestId
        ? {
            onInterventionPrepared: () => {
              approvalClaim.continuationPrepared = true;
            },
          }
        : {}),
      maxSteps,
      modelRuntimeConfig: { ...modelCapabilities, model, provider },
      hooks,
      operationId,
      parentOperationId,
      reservedOperation,
      signal,
      queueRetries,
      queueRetryDelay,
      stream,
      userId: deps.userId,
      userInterventionConfig,
      workspaceId: deps.workspaceId,
    });
    approvalClaim.continuationStarted = true;
    if (result.autoStarted) input.onScheduled?.();

    // The approval continuation is a fresh operation. Legacy direct callers
    // retire the old parked runtime here, only after createOperation has
    // durably scheduled the replacement. Generic v2 calls carry a durable
    // resolution id and defer this transition to the shared router dispatch
    // boundary, which can retry it without losing this successful ExecAgent
    // result (and therefore the WebSocket subscription credentials).
    if (approvalSourceOperationId && !providedApprovalResolutionRequestId) {
      await deps.retirePendingApprovalOperation(approvalSourceOperationId);
    }

    log('execAgent: created operation %s (autoStarted: %s)', operationId, result.autoStarted);

    // Persist running operation to topic metadata for reconnect after page reload.
    //
    // Skipped for isolation-thread children (callAgent / callSubAgent / group
    // members): they run on the SPAWNER's topic and finish long before it does,
    // so claiming the mark would first point every client reconnect at the
    // child's thread stream, and then β€” once the child finished and cleared it β€”
    // leave the still-running parent with no mark at all, i.e. no gateway
    // WebSocket for the rest of the run. The parent's mark stays authoritative;
    // a child's live progress already rides down the parent channel via
    // `appContext.subAgentProgress`.
    // `orchestrationRole` is public rendering metadata. Only the internally
    // propagated parent operation id proves child ownership of this topic.
    if (ownsRootTopic && !markTopicRunning) {
      await deps.topicModel.updateMetadata(topicId, {
        runningOperation: {
          assistantMessageId,
          heteroType: null,
          operationId,
          scope: appContext?.scope ?? undefined,
          // Liveness stamp β€” without it this marker can never be proven dead
          // and would hold the topic against background starts forever.
          startedAt: new Date().toISOString(),
          threadId: appContext?.threadId ?? undefined,
        },
      });
    }

    // An explicit auto-start request can still return an unstarted operation
    // (no queue implementation); it must not leave an unattended topic spinning.
    if (markTopicRunning && !result.autoStarted) {
      await deps.topicModel.settleRunningOperation(topicId, operationId, 'active');
    }

    // Generate a short-lived JWT for Gateway WebSocket authentication.
    // Share-visitor runs sign for the VISITOR: signUserJWT mints a full
    // oidcAuth token, so a creator-signed token handed to the visitor's
    // browser would be creator account access. The gateway channel is
    // registered under the visitor's id (`streamOwnerUserId`), so the
    // visitor's own `sub` matches.
    let gatewayToken: string | undefined;
    if (!deps.withholdGatewayToken) {
      try {
        gatewayToken = await traceStartStage('sign_gateway_token', () =>
          signUserJWT(shareGate?.visitorUserId ?? deps.userId),
        );
      } catch {
        log('execAgent: failed to sign gateway JWT, gateway auth will be unavailable');
      }
    }

    return {
      agentId: resolvedAgentId,
      assistantMessageId,
      autoStarted: result.autoStarted,
      createdAt: new Date().toISOString(),
      heteroType: null,
      message: 'Agent operation created successfully',
      messageId: result.messageId,
      operationId,
      status: 'created',
      success: true,
      timestamp: new Date().toISOString(),
      token: gatewayToken,
      topicId,
      userMessageId: userMessageId ?? parentMessageId ?? '',
    };
  } catch (error) {
    if (markTopicRunning) {
      // Compare-and-settle preserves a newer run and never drops a marker
      // separately from its state, including aborts and errors after preparation.
      try {
        await deps.topicModel.settleRunningOperation(topicId, operationId, 'active');
      } catch (cleanupError) {
        console.error('[startOperation] Failed to settle an opted-in startup', cleanupError);
      }
    }
    if (topicStartOwnerOperationId) {
      await deps.topicModel.removeRunningOperationChild(topicId, operationId).catch(() => false);
    }
    if (isAbortError(error)) {
      await updateAbortedAssistantMessage(error.message);
      log('execAgent: createOperation aborted for %s: %s', operationId, error.message);
      throw error;
    }
    if (providedApprovalResolutionRequestId && approvalClaim.continuationPrepared) {
      // The source claim + deterministic state are now the retry record. A
      // queue ACK may have been accepted even when its HTTP response or our
      // follow-up marker write failed, so do not paint the stable assistant
      // as terminal error and do not collapse this into success:false.
      throw error;
    }

    // Operation startup failed (e.g., QStash queue service unavailable)
    // Update assistant message with error so user can see what went wrong
    const errorMessage = error instanceof Error ? error.message : 'Unknown error starting agent';
    log(
      'execAgent: createOperation failed, updating assistant message with error: %s',
      errorMessage,
    );

    await deps.messageModel.update(assistantMessageId, {
      content: '',
      error: {
        body: {
          detail: errorMessage,
        },
        message: errorMessage,
        type: 'ServerAgentRuntimeError', // ServiceUnavailable - agent runtime service unavailable
      },
    });

    // Return result with error status - messages are valid but agent didn't start
    return {
      agentId: resolvedAgentId,
      assistantMessageId,
      autoStarted: false,
      createdAt: new Date().toISOString(),
      error: errorMessage,
      message: 'Agent operation failed to start',
      operationId,
      status: 'error',
      success: false,
      timestamp: new Date().toISOString(),
      topicId,
      userMessageId: userMessageId ?? parentMessageId ?? '',
    };
  }
};