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.

49.6 KB
Raw Blame
import { isHeterogeneousAgentModelId, LOADING_FLAT } from '@lobechat/const';
import type { LobeChatDatabase } from '@lobechat/database';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import type {
  AgentSenderMetadata,
  ChatAudioItem,
  ChatFileItem,
  ChatTopicMetadata,
  ChatVideoItem,
  FileAccessScope,
  HeterogeneousProviderConfig,
  HeterogeneousRuntimePinSources,
  HeterogeneousTopicPin,
} from '@lobechat/types';
import {
  agentShareFileAccessScope,
  ordinaryFileAccessScope,
  resolveHeterogeneousModelOverride,
  resolveHeterogeneousProviderTopicModel,
  resolveHeterogeneousTopicRuntimeSnapshot,
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';

import { AiModelModel } from '@/database/models/aiModel';
import type { MessageModel } from '@/database/models/message';
import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';
import type { TopicModel } from '@/database/models/topic';
import { defaultsToAuto } from '@/helpers/executionTarget';
import { resolveModelExtendParamsForUser } from '@/server/modules/AgentRuntime/adapters/serverCallLlmContextHints';
import type { AgentConfigWithId } from '@/server/services/agent';
import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { shouldSuppressSignal } from '@/server/services/agentSignal/suppressSignal';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
import { resolveAttachmentsByFileIds } from '@/server/services/file/resolveAttachments';
import { toTitleText } from '@/utils/markdownToTxt';

import type { DeviceAccessReason } from '../deviceAccessPolicy';
import { resolveDeviceAccessPolicy } from '../deviceAccessPolicy';
import { ingestAttachment } from '../ingestAttachment';
import type { AgentShareGate } from '../shareGate';
import { reserveShareVisitorTopic, reserveShareVisitorTurn } from '../shareVisitorAbuseGuards';
import type { InternalExecAgentParams } from '../types';
import { buildNewTopicMetadata, resolveTopicOpenedBy } from './newTopicMetadata';
import { createUserTurnAnchor } from './resolveUserMessageParentId';
import { createStageTracer, openStageMark } from './sendTracing';
import { assertShareHeteroAllowed } from './shareHeteroGate';
import { resolveTurnProjectId, withProjectSandbox } from './topicProject';
import { buildUserTurnMetadata } from './userTurnMetadata';

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

const traceTurnStage = createStageTracer('turn_setup');
const openTurnStage = openStageMark('turn_setup');

export interface TurnSetupDeps {
  db: LobeChatDatabase;
  messageModel: MessageModel;
  topicModel: TopicModel;
  userId: string;
  workspaceId?: string;
}

export interface RunAttachments {
  audioList?: ChatAudioItem[];
  fileIds?: string[];
  fileList?: ChatFileItem[];
  imageList?: Array<{ alt: string; id: string; url: string }>;
  videoList?: ChatVideoItem[];
  warnings: string[];
}

/**
 * Build the reasoning snapshot for a topic being created β€” see
 * `ChatTopicMetadata.reasoningConfig` / `heteroEffort` / `heteroSpeed`. Returns
 * undefined when there is nothing to pin (non-reasoning model, hetero agent
 * without effort or speed)
 * so the caller leaves metadata untouched. Never throws: a failed lookup just
 * means the topic follows the user-level config until the user pins one.
 */
const resolveTopicReasoningSnapshot = async ({
  deps,
  heterogeneousProvider,
  isHeteroTopic,
  model,
  provider,
}: {
  deps: Pick<TurnSetupDeps, 'db' | 'userId' | 'workspaceId'>;
  heterogeneousProvider: HeterogeneousProviderConfig | undefined;
  isHeteroTopic: boolean;
  model: string;
  provider: string;
}): Promise<
  Pick<ChatTopicMetadata, 'heteroEffort' | 'heteroSpeed' | 'reasoningConfig'> | undefined
> => {
  if (isHeteroTopic) {
    const snapshot = resolveHeterogeneousTopicRuntimeSnapshot(heterogeneousProvider);
    return Object.keys(snapshot).length === 0 ? undefined : snapshot;
  }

  try {
    const aiModelModel = new AiModelModel(deps.db, deps.userId, deps.workspaceId);
    const { modelHasReasoningExtendParams } = await resolveModelExtendParamsForUser({
      aiModelModel,
      model,
      provider,
    });
    if (!modelHasReasoningExtendParams) return undefined;

    const reasoningConfig = await aiModelModel.getModelReasoningConfig(model, provider);
    return { reasoningConfig: reasoningConfig ?? {} };
  } catch (error) {
    log('execAgent: failed to snapshot topic reasoning config for %s: %O', model, error);
    return undefined;
  }
};

/** Snapshot only newly created topics, including callers that pre-create before setupTurn. */
export const resolveNewTopicSnapshot = async (
  deps: Pick<TurnSetupDeps, 'db' | 'userId' | 'workspaceId'>,
  agentConfig: AgentConfigWithId,
  overrides?: { model?: string; provider?: string },
) => {
  const model = overrides?.model ?? agentConfig.model!;
  const provider = overrides?.provider ?? agentConfig.provider!;
  const heterogeneousProvider = agentConfig.agencyConfig?.heterogeneousProvider;
  const heteroType =
    heterogeneousProvider?.type ?? (isHeterogeneousAgentModelId(model) ? model : undefined);
  const heteroModel = heterogeneousProvider
    ? resolveHeterogeneousProviderTopicModel(heterogeneousProvider)
    : undefined;
  return {
    metadata: await resolveTopicReasoningSnapshot({
      deps,
      heterogeneousProvider,
      isHeteroTopic: !!heteroType,
      model,
      provider,
    }),
    model: heteroModel?.model ?? (heteroType ? undefined : model),
    provider: heteroModel?.provider ?? heteroType ?? provider,
  };
};

/**
 * Resolve a run's attachments into the lists the message + context layers
 * consume. This is the single standard ingestion path shared by BOTH branches
 * of {@link AiAgentService.execAgent} β€” the heterogeneous-agent branch (which
 * returns early) and the normal agent branch β€” so neither hand-rolls its own
 * upload.
 *
 * Two sources are merged:
 * - `files`: raw buffers / URLs delivered by bot/IM channels (Slack, Telegram,
 *   …). These have never touched our storage, so they're uploaded to S3 here.
 * - `attachedFileIds`: already-uploaded ids (the SPA gateway path). Resolved to
 *   signed URLs and classified via {@link resolveAttachmentsByFileIds}.
 *
 * Per-file ingestion failures are collected into `warnings` and never thrown,
 * so a single bad attachment can't block the run (the text prompt still works).
 */
const resolveRunAttachments = async (
  deps: TurnSetupDeps,
  {
    attachedFileIds,
    fileAccessScope,
    files,
    throwIfAborted,
  }: {
    attachedFileIds?: string[];
    fileAccessScope: FileAccessScope;
    files?: InternalExecAgentParams['files'];
    throwIfAborted: (stage: string) => Promise<void>;
  },
): Promise<RunAttachments> => {
  const warnings: string[] = [];
  let fileIds: string[] | undefined;
  let imageList: Array<{ alt: string; id: string; url: string }> | undefined;
  let videoList: ChatVideoItem[] | undefined;
  let audioList: ChatAudioItem[] | undefined;
  let fileList: ChatFileItem[] | undefined;

  // Upload raw bot/IM files to S3 and classify them (image / video / audio / document).
  if (files && files.length > 0) {
    fileIds = [];
    imageList = [];
    videoList = [];
    audioList = [];
    fileList = [];
    const fileService = new FileService(deps.db, deps.userId, deps.workspaceId);
    const documentService = new DocumentService(deps.db, deps.userId, deps.workspaceId);

    for (const file of files) {
      await throwIfAborted('file upload');

      try {
        const result = await ingestAttachment(file, fileService, deps.userId, deps.workspaceId);
        fileIds.push(result.fileId);

        if (result.isImage) {
          imageList.push({
            alt: file.name || 'image',
            id: result.fileId,
            url: result.resolvedUrl,
          });
          continue;
        }

        if (result.isVideo) {
          videoList.push({
            alt: file.name || 'video',
            id: result.fileId,
            url: result.resolvedUrl,
          });
          continue;
        }

        if (result.isAudio) {
          audioList.push({
            alt: file.name || 'audio',
            id: result.fileId,
            url: result.resolvedUrl,
          });
          continue;
        }

        // Non-image / non-video / non-audio: parse file content into the documents table so
        // the MessageContentProcessor can inject it via filesPrompts(). Mirrors
        // what the web upload path does, ensuring bot-uploaded PDFs / text /
        // JSON / .skill files are actually visible to the LLM (instead of
        // being silently uploaded but never read).
        let content: string | undefined;
        try {
          const document = await documentService.parseFile(result.fileId);
          content = document.content ?? undefined;
        } catch (parseError) {
          log(
            'execAgent: parseFile failed for %s (fileId=%s): %O',
            file.name,
            result.fileId,
            parseError,
          );
          warnings.push(
            `File "${file.name || 'unknown'}" was uploaded but its contents could not be extracted.`,
          );
        }

        fileList.push({
          content,
          fileType: file.mimeType ?? 'application/octet-stream',
          id: result.fileId,
          name: file.name ?? 'file',
          size: file.size ?? 0,
          url: result.resolvedUrl || '',
        });
      } catch (error) {
        log('execAgent: failed to ingest file %s: %O', file.name || file.url, error);
        // A quota rejection is actionable, so name it rather than leaving the
        // sender to guess why every attachment silently vanished.
        warnings.push(
          (error as { code?: string })?.code === 'FORBIDDEN'
            ? `File "${file.name || 'unknown'}" was skipped: storage limit reached.`
            : `File "${file.name || 'unknown'}" could not be uploaded and was skipped.`,
        );
      }
    }

    if (fileIds.length > 0) {
      log(
        'execAgent: uploaded %d files to S3 (%d images, %d videos, %d audios, %d documents)',
        fileIds.length,
        imageList.length,
        videoList.length,
        audioList.length,
        fileList.length,
      );
    }
    if (imageList.length === 0) imageList = undefined;
    if (videoList.length === 0) videoList = undefined;
    if (audioList.length === 0) audioList = undefined;
    if (fileList.length === 0) fileList = undefined;
  }

  // Attach already-uploaded files referenced by fileIds (e.g. SPA Gateway mode).
  // These files are already in the `files` table; resolve URLs + classify, and
  // merge into the imageList/videoList/fileList passed to the LLM and stored
  // as message relations via messagesFiles.
  if (attachedFileIds && attachedFileIds.length > 0) {
    await throwIfAborted('file resolution');

    try {
      const resolved = await resolveAttachmentsByFileIds({
        db: deps.db,
        fileAccessScope,
        fileIds: attachedFileIds,
        userId: deps.userId,
        workspaceId: deps.workspaceId,
      });

      warnings.push(...resolved.warnings);

      if (resolved.orderedFileIds.length > 0) {
        fileIds = [...(fileIds ?? []), ...resolved.orderedFileIds];

        if (resolved.imageList.length > 0) {
          imageList = [...(imageList ?? []), ...resolved.imageList];
        }
        if (resolved.videoList.length > 0) {
          videoList = [...(videoList ?? []), ...resolved.videoList];
        }
        if (resolved.audioList.length > 0) {
          audioList = [...(audioList ?? []), ...resolved.audioList];
        }
        if (resolved.fileList.length > 0) {
          fileList = [...(fileList ?? []), ...resolved.fileList];
        }
      }
    } catch (err) {
      // Non-fatal: a resolver hiccup (S3 / DB blip) must not block the run β€”
      // the text prompt still works. Persist the file→message relation anyway
      // so the attachment isn't lost; only its preview / parsed content is.
      log('execAgent: attachment resolution failed, continuing without previews: %O', err);
      fileIds = Array.from(new Set([...(fileIds ?? []), ...attachedFileIds]));
    }
  }

  // Normalize an empty (all-failed) upload to undefined so callers don't attach
  // an empty messagesFiles relation.
  if (fileIds && fileIds.length === 0) fileIds = undefined;

  return { audioList, fileIds, fileList, imageList, videoList, warnings };
};

export interface TurnSetupInput {
  agentConfig: AgentConfigWithId;
  /**
   * Sending agent of an agent β†’ agent turn, resolved to a snapshot before this
   * stage runs. Stamped onto the user message as `metadata.agentSender` so the
   * receiving topic attributes the turn to that agent, not the human owner.
   */
  agentSender?: AgentSenderMetadata;
  agentSlug?: string | null;
  appContext?: InternalExecAgentParams['appContext'];
  assistantAgentId: string;
  attachedFileIds?: string[];
  /** Spine anchor for a batch approval β€” overrides the assistant's parent. */
  batchApprovalAnchorId?: string;
  botContext?: InternalExecAgentParams['botContext'];
  botSender?: InternalExecAgentParams['botSender'];
  clientIds?: InternalExecAgentParams['clientIds'];
  /** Stable assistant id for a generic intervention continuation. */
  continuationAssistantId?: string;
  conversationAgentId: string;
  createdThreadId?: string;
  cronJobId?: string;
  externalOrigin?: InternalExecAgentParams['externalOrigin'];
  files?: InternalExecAgentParams['files'];
  /** Whether the turn @-mentions agents in a non-group conversation. */
  hasMentionedAgents?: boolean;
  modelOverride?: string;
  /** See `ExecAgentParams.openedByTopicId`. */
  openedByTopicId?: string;
  operationTaskId?: string;
  parentMessageId?: string;
  persistedUserMessageId?: string;
  prompt: string;
  providerOverride?: string;
  requestedDeviceId?: string;
  /** See `InternalExecAgentParams.requireDevice`. */
  requireDevice?: boolean;
  reservedOperationId?: string;
  resolvedAgentId: string;
  /** Raw resume flag β€” a resume run must land on an existing topic. */
  resume?: boolean;
  runFromHistory: boolean;
  /** Skills the user selected for this turn; see `ExecAgentParams.selectedSkillIds`. */
  selectedSkillIds?: string[];
  /** Tools the user selected for this turn; see `ExecAgentParams.selectedToolIds`. */
  selectedToolIds?: string[];
  /** Shared-agent visitor gate β€” set only by the shareChat router. */
  shareGate?: AgentShareGate;
  /** The prompt was queued behind a running turn; see `ExecAgentParams.steer`. */
  steer?: boolean;
  throwIfExecutionAborted: (stage: string) => Promise<void>;
  title?: string;
  trigger?: string;
  /** The composer-authored part of the user message; see `ExecAgentParams.userMessage`. */
  userMessage?: InternalExecAgentParams['userMessage'];
  webhookThread?: InternalExecAgentParams['webhookThread'];
}

export interface TurnSetupResult {
  assistantMessageId: string;
  canUseDevice: boolean;
  deviceAccessReason: DeviceAccessReason;
  /** The agent a builder run edits β€” from the request, else recovered from the builder topic. */
  editingAgentId?: string;
  effectiveRequestedDeviceId?: string;
  heterogeneousProvider?: NonNullable<AgentConfigWithId['agencyConfig']>['heterogeneousProvider'];
  heteroType: HeterogeneousAgentType;
  isFixedDeviceTarget: boolean;
  isHeteroAgent: boolean;
  /** Effective model/provider after the topic-pinned model is applied. */
  model: string;
  /**
   * Model, effort and speed pins for a heterogeneous run: a reused topic's pins,
   * with a native Task model override taking the model's place.
   */
  pinnedHeterogeneousTopicModel?: HeterogeneousTopicPin;
  /** Which layer supplied each pin, for the dispatched configuration receipt. */
  pinnedHeterogeneousTopicSources?: HeterogeneousRuntimePinSources;
  /** Project the turn runs in β€” see `resolveTurnProjectId`. */
  projectId?: string;
  provider: string;
  /**
   * The request's device, or β€” when it named none β€” the device a reused topic
   * is bound to. Use this instead of the raw request value downstream.
   */
  requestedDeviceId?: string;
  /** Metadata persisted on this turn's user message; see `buildUserTurnMetadata`. */
  requestTriggerMetadata: ReturnType<typeof buildUserTurnMetadata>;
  runAttachments: RunAttachments;
  /** Rows THIS turn persisted β€” the history loader must exclude them. */
  selfMessageIds: Set<string>;
  topicBoundDeviceId?: string | null;
  /**
   * The group a reused Group Agent Builder topic was opened on
   * (`metadata.editingGroupId`), for runs whose request does not name it.
   */
  topicEditingGroupId?: string;
  topicId: string;
  userMessageId?: string;
}

/** The agent's fixed execution target would drop a device the caller required. */
export class RequestedDeviceIgnoredError extends Error {
  constructor(readonly deviceId: string) {
    super(
      `This agent always runs on its configured execution target, so device ${deviceId} would be ignored. Drop the device, or have a workspace admin change the agent's execution target.`,
    );
    this.name = 'RequestedDeviceIgnoredError';
  }
}

/**
 * Stage 3 + the shared turn setup of {@link AiAgentService.execAgent}: topic
 * creation/reuse (with the topic-pinned model), device-access policy, hetero
 * detection, attachment ingestion, and persisting the user + assistant turn.
 *
 * Everything here runs for BOTH hetero and normal agents, so it lives before
 * the execution fork and both branches consume the same records. Keeping it in
 * one place is what guarantees the hetero path can't drift from the standard
 * path again (the bot-image bug came from the hetero branch re-implementing β€”
 * and skipping β€” this step).
 */
export const setupTurn = async (
  deps: TurnSetupDeps,
  input: TurnSetupInput,
): Promise<TurnSetupResult> => {
  const {
    agentConfig,
    agentSlug,
    agentSender,
    appContext,
    assistantAgentId,
    attachedFileIds,
    batchApprovalAnchorId,
    botContext,
    botSender,
    clientIds,
    continuationAssistantId,
    conversationAgentId,
    createdThreadId,
    externalOrigin,
    cronJobId,
    webhookThread,
    openedByTopicId,
    files,
    hasMentionedAgents,
    modelOverride,
    operationTaskId,
    parentMessageId,
    persistedUserMessageId,
    prompt,
    providerOverride,
    requestedDeviceId,
    requireDevice,
    reservedOperationId,
    resolvedAgentId,
    resume,
    runFromHistory,
    selectedSkillIds,
    selectedToolIds,
    shareGate,
    steer,
    throwIfExecutionAborted,
    title,
    trigger,
    userMessage,
  } = input;

  let topicId = appContext?.topicId;
  let editingAgentId = appContext?.editingAgentId;
  let turnProjectId: string | undefined;

  const isFixedExecutionTargetSelection =
    !!deps.workspaceId && agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';
  const isFixedDeviceTarget =
    isFixedExecutionTargetSelection && agentConfig.agencyConfig?.executionTarget === 'device';
  // A caller that needs the run on its device (`lh topic send --new --device`)
  // must not be told it was sent there when the fixed target drops the device.
  // `agentConfig` already carries the caller's EFFECTIVE policy (a managing
  // caller's or a private agent's fixed policy is lifted upstream, in
  // `resolveRunAgentConfig`), and nothing is written yet.
  if (
    requireDevice &&
    requestedDeviceId &&
    isFixedExecutionTargetSelection &&
    !(isFixedDeviceTarget && agentConfig.agencyConfig?.boundDeviceId === requestedDeviceId)
  ) {
    throw new RequestedDeviceIgnoredError(requestedDeviceId);
  }
  // `let`: a reused topic that already ran on a machine supplies the device
  // when the request names none (see the reuse branch below).
  let resolvedRequestedDeviceId = requestedDeviceId;
  let effectiveRequestedDeviceId = isFixedExecutionTargetSelection ? undefined : requestedDeviceId;
  let topicBoundDeviceId = isFixedDeviceTarget
    ? agentConfig.agencyConfig?.boundDeviceId
    : isFixedExecutionTargetSelection
      ? undefined
      : requestedDeviceId;

  // Effective model/provider for this run. Defaults to the agent config, but a
  // topic pins its own model in the top-level `topics.model`/`provider` columns
  // (config source of truth) β€” snapshotted on creation, and honored below when
  // reusing a topic whose model was switched while active. Keeps the Gateway/
  // cloud path in sync with the client local path (see streamingExecutor +
  // getTopicModelById).
  let model = agentConfig.model!;
  let provider = agentConfig.provider!;
  const heterogeneousProvider = agentConfig.agencyConfig?.heterogeneousProvider;
  let pinnedHeterogeneousTopicModel: HeterogeneousTopicPin | undefined;
  let pinnedHeterogeneousTopicSources: HeterogeneousRuntimePinSources | undefined;
  // TaskRunner forwards the Task's model snapshot on every run. For a
  // heterogeneous agent that snapshot is often the Agent row's wrapper pair (a
  // runtime ID such as codex/openai, or an ordinary chat model), not a CLI
  // model, so only a runtime-compatible override may replace a topic pin.
  const heterogeneousModelOverride =
    heterogeneousProvider && modelOverride
      ? resolveHeterogeneousModelOverride(heterogeneousProvider, {
          model: modelOverride,
          provider: providerOverride,
        })
      : undefined;
  const nativeModelOverride = heterogeneousProvider
    ? heterogeneousModelOverride?.model
    : modelOverride;
  const nativeProviderOverride = heterogeneousProvider
    ? heterogeneousModelOverride?.provider
    : providerOverride;
  let topicEditingGroupId: string | undefined;

  // Share visitors run a local CLI Agent only on the granted device. Checked
  // against the agent-level config before any row is written, and re-asserted
  // once a reused topic's pinned model and device are applied.
  const assertShareHetero = async (runModel: string) => {
    const shareDeviceId = await assertShareHeteroAllowed({
      agencyConfig: agentConfig.agencyConfig,
      db: deps.db,
      heterogeneousType: heterogeneousProvider?.type,
      model: runModel,
      ownerUserId: deps.userId,
      requestedDeviceId: resolvedRequestedDeviceId,
      shareGate,
      trigger,
      workspaceId: deps.workspaceId,
    });
    // Route the dispatch to the device the gate selected (an `auto` Agent's
    // single online device), which the dispatch would not find on its own.
    // Only the dispatch gets it: pinning the topic to an automatic pick would
    // keep a later turn on that device after it goes offline and another one
    // is online.
    if (shareDeviceId && !resolvedRequestedDeviceId && !isFixedExecutionTargetSelection)
      resolvedRequestedDeviceId = shareDeviceId;
  };
  await assertShareHetero(model);

  const assertProjectDirectoryAccess = () => {
    if (shareGate || (botContext && !resolveDeviceAccessPolicy({ botContext }).canUseDevice))
      throw new Error('Project directory access denied');
  };
  /** Pin the run to the device a project directory lives on β€” only it can honour the run. */
  const routeToProjectDirectory = async (directory: { deviceId: string | null }) => {
    if (
      agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
      agentConfig.agencyConfig.boundDeviceId !== directory.deviceId
    )
      throw new Error('Agent is fixed to another execution target');
    // Reject an unavailable device *here*, before the user/assistant rows are
    // persisted: the client treats a rejected send as never accepted, keeps the
    // draft and rolls back its optimistic pair, so a later rejection would leave
    // a failed turn durable server-side that the client disagrees with.
    // Liveness comes from the gateway's device listing β€” not a device round
    // trip β€” so the send path keeps the latency fix, and the dispatch remains
    // the authority on whether the directory still exists on the device.
    const { canUseDevice: canUseProjectDevice } = resolveDeviceAccessPolicy({ botContext });
    const projectDevices = canUseProjectDevice
      ? await getScopedOnlineDevices(deps.db, deps.userId, deps.workspaceId)
      : [];
    if (!projectDevices.some((device) => device.deviceId === directory.deviceId && device.online))
      throw new Error('Device is offline or working directory is unavailable');
    const deviceId = directory.deviceId ?? undefined;
    resolvedRequestedDeviceId = deviceId;
    effectiveRequestedDeviceId = deviceId;
    topicBoundDeviceId = deviceId;
    agentConfig.agencyConfig = {
      ...agentConfig.agencyConfig,
      boundDeviceId: deviceId,
      executionTarget: 'device',
    };
  };

  // Topic resolution assigns the turn's narrowed bindings (topic id, pinned
  // model, device targets), so it is a marked block rather than a callback:
  // every exit, including a throw, records the error and closes the span.
  const topicStage = openTurnStage('topic');
  try {
    if (!topicId) {
      if (resume) {
        throw new Error('Resume mode requires the parent message to belong to a topic');
      }

      // A blank conversation opened from a project group's "+" is born inside
      // that directory: bound to it, and run on the device it lives on.
      let projectDirectory:
        Awaited<ReturnType<ProjectWorkingDirectoryModel['resolve']>> | undefined;
      if (appContext?.projectWorkingDirectoryId) {
        assertProjectDirectoryAccess();
        projectDirectory = await new ProjectWorkingDirectoryModel(
          deps.db,
          deps.userId,
          deps.workspaceId,
        ).resolve(appContext.projectWorkingDirectoryId);
        await routeToProjectDirectory(projectDirectory);
      }

      const openedBy = await resolveTopicOpenedBy(deps.topicModel, openedByTopicId);
      const metadata = buildNewTopicMetadata({
        appContext,
        botContext,
        cronJobId,
        deviceBindingPinned: Boolean(effectiveRequestedDeviceId),
        editingAgentId,
        openedBy,
        projectDirectory,
        taskId: operationTaskId,
        topicBoundDeviceId,
        webhookThread,
      });
      turnProjectId = await resolveTurnProjectId(deps, {
        directoryProjectId: projectDirectory?.projectId,
        requestedProjectId: appContext?.projectId,
        shareGate,
        taskId: operationTaskId,
      });

      const fallbackTitleSource = toTitleText(prompt);
      const snapshot = await resolveNewTopicSnapshot(deps, agentConfig);
      const metadataWithSnapshot = await withProjectSandbox(deps, {
        agentId: resolvedAgentId,
        hasDirectory: !!projectDirectory,
        metadata: metadata || snapshot.metadata ? { ...metadata, ...snapshot.metadata } : undefined,
        projectId: turnProjectId,
      });
      // Second argument: the id the client already rendered this topic under
      // (sidebar row, message bucket). Absent β†’ the model mints one as before.
      const newTopicParams = {
        agentId: resolvedAgentId,
        // Persist the group association when running inside a group conversation.
        // Without it the topic is created group-less and only shows under the
        // member agent's topic list β€” never in the group sidebar (which queries
        // `topics.groupId`), so the conversation silently "disappears" from the
        // group. execGroupAgent normally pre-creates the topic, but any path
        // that reaches execAgent without a topicId (e.g. the async/queue run)
        // must carry the groupId through too (group topic sidebar + ownership fix).
        groupId: appContext?.groupId,
        metadata: metadataWithSnapshot,
        projectId: turnProjectId,
        projectWorkingDirectoryId: projectDirectory?.id,
        // Snapshot the effective model as the topic's pinned model (config).
        model: snapshot.model,
        provider: snapshot.provider,
        // Share-visitor runs: the topic row belongs to the creator
        // (`deps.userId`), but stamping the visitor's id here is what
        // `TopicModel`'s creator-facing reads (`query`, `count`, `queryTopics`,
        // `queryRecent`, `rank`) filter out via `notShareVisitorTopic()`, and
        // what lets shareChat scope reads per visitor (`queryBySender` /
        // `countMessagesBySender`).
        senderId: shareGate?.visitorUserId,
        title:
          title !== undefined
            ? title
            : fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : ''),
        trigger,
      };
      // Share-visitor runs insert the topic only under the share's row lock, so
      // a share paused mid-request writes nothing β€” see
      // `reserveShareVisitorTopic`'s JSDoc. Non-share runs keep the plain insert.
      const newTopic = shareGate
        ? await reserveShareVisitorTopic(
            {
              agentId: resolvedAgentId,
              db: deps.db,
              expectedShareId: shareGate.shareId,
              ownerId: deps.userId,
              visitorUserId: shareGate.visitorUserId,
              workspaceId: deps.workspaceId,
            },
            newTopicParams,
            clientIds?.topicId,
          )
        : await deps.topicModel.create(newTopicParams, clientIds?.topicId);
      topicId = newTopic.id;
      log(
        'execAgent: created new topic %s with trigger %s, groupId %s, cronJobId %s',
        topicId,
        trigger || 'default',
        appContext?.groupId || 'none',
        cronJobId || 'none',
      );
    } else {
      log('execAgent: reusing existing topic %s', topicId);

      // Honor a topic-pinned model (snapshotted on creation, updated when the
      // user switched model while the topic was active) over the agent default.
      // Explicit per-run values (such as callSubAgent) override their own field.
      // The pinned model lives in the top-level `topics.model`/`provider` columns
      // (config source of truth), NOT in metadata.
      const existingTopic = await deps.topicModel.findById(topicId);
      const pendingRun = existingTopic?.metadata?.scheduledRun;
      if (
        existingTopic?.status === 'scheduled' &&
        pendingRun?.kind === 'worktree_start' &&
        pendingRun.operationId !== reservedOperationId
      ) {
        throw new TRPCError({
          code: 'CONFLICT',
          message: 'This conversation is preparing its worktree.',
        });
      }
      topicEditingGroupId = existingTopic?.metadata?.editingGroupId ?? undefined;
      turnProjectId = await resolveTurnProjectId(deps, {
        shareGate,
        taskId: operationTaskId,
        topicProjectId: existingTopic?.projectId ?? null,
      });
      // A project conversation without a directory follows the plain
      // topic-pinned device path below, like any other conversation.
      if (existingTopic?.projectWorkingDirectoryId) {
        assertProjectDirectoryAccess();
        const directory = await new ProjectWorkingDirectoryModel(
          deps.db,
          deps.userId,
          deps.workspaceId,
        ).resolveForTopic(topicId);
        if (!directory) throw new Error('Project directory binding no longer exists');
        await routeToProjectDirectory(directory);
      }

      // Fail-closed guard: a non-share run must never operate on a share-visitor
      // topic. `findById` is ownership-scoped but deliberately does NOT exclude
      // visitor topics (see its JSDoc) β€” they carry the CREATOR's own userId for
      // billing attribution, so `deps.userId`'s ownership check alone lets a
      // creator-authenticated but non-share call (e.g. hitting `aiAgent.execAgent`
      // directly with a leaked/guessed visitor topicId) load a visitor
      // conversation as if it were their own. A share visitor's own run is
      // authorized separately via `shareGate` β€” already re-validated upstream by
      // `findVisitorTopicOrThrow` in `shareChat.ts` β€” and must keep working.
      if (!shareGate && existingTopic?.senderId) {
        throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });
      }

      /** A group topic pins its owning agent; member runs keep their own model and effort. */
      const canUseTopicPin = !existingTopic?.groupId || existingTopic.agentId === resolvedAgentId;
      // The model pin belongs to the topic's own agent. A `callAgent` child runs
      // in an isolation thread on the CALLER's topic; inheriting that pin would
      // run the callee on the caller's model (#19542). Legacy topics without an
      // owner keep the pin.
      const canUseTopicModelPin =
        canUseTopicPin && (!existingTopic?.agentId || existingTopic.agentId === resolvedAgentId);
      const pinnedModel = canUseTopicModelPin ? existingTopic?.model : undefined;
      if (pinnedModel) {
        model = nativeModelOverride || pinnedModel;
        provider = nativeProviderOverride || existingTopic?.provider || provider;
        pinnedHeterogeneousTopicModel = { model, provider };
        log(
          'execAgent: using topic-pinned model=%s provider=%s for topic %s',
          model,
          provider,
          topicId,
        );
      }
      // Effort and speed pins live in metadata and are independent of the model
      // pin (a runtime without a model selector can still pin them). They belong
      // to the topic's own agent for the same reason as the model pin.
      const pinnedHeteroEffort = canUseTopicModelPin
        ? existingTopic?.metadata?.heteroEffort
        : undefined;
      const pinnedHeteroSpeed = canUseTopicModelPin
        ? existingTopic?.metadata?.heteroSpeed
        : undefined;
      if (pinnedHeteroEffort !== undefined || pinnedHeteroSpeed !== undefined) {
        pinnedHeterogeneousTopicModel = {
          ...pinnedHeterogeneousTopicModel,
          ...(pinnedHeteroEffort === undefined ? {} : { effort: pinnedHeteroEffort }),
          ...(pinnedHeteroSpeed === undefined ? {} : { speed: pinnedHeteroSpeed }),
        };
      }

      // A conversation stays on the machine it already ran on: its cwd and CLI
      // session live there, so the agent-level target (the default for NEW
      // topics) must not move a later turn elsewhere. An explicit request device
      // (the picker's in-process preset, a task/sub-agent override) and a fixed
      // workspace target still win. `auto` picked a fresh online device every
      // run, so its own earlier pick never pins the conversation β€” but a device
      // the caller chose explicitly did (see `deviceBindingPinned` below).
      const topicPinnedDeviceId = canUseTopicPin
        ? existingTopic?.metadata?.boundDeviceId
        : undefined;
      // A binding the caller chose for this conversation (`--device`, the
      // composer preset, a project directory) is a promise, not an auto pick:
      // later turns stay there even for an `auto` agent, which would otherwise
      // grab whichever machine is online now.
      const topicDeviceBindingPinned =
        canUseTopicPin && existingTopic?.metadata?.deviceBindingPinned === true;
      // An unset target is the same default as `auto` (see `defaultsToAuto`), so
      // both re-pick a device on every turn instead of resurrecting an earlier
      // pick β€” only a binding the caller chose explicitly pins the conversation.
      const autoTargetSelected =
        agentConfig.agencyConfig?.executionTarget === 'auto' ||
        defaultsToAuto(agentConfig.agencyConfig, isHeterogeneousAgentModelId(model));
      // A project-directory topic already routed to its directory's device above.
      if (
        !requestedDeviceId &&
        !existingTopic?.projectWorkingDirectoryId &&
        topicPinnedDeviceId &&
        !isFixedExecutionTargetSelection &&
        (!autoTargetSelected || topicDeviceBindingPinned)
      ) {
        resolvedRequestedDeviceId = topicPinnedDeviceId;
        effectiveRequestedDeviceId = topicPinnedDeviceId;
        topicBoundDeviceId = topicPinnedDeviceId;
        log('execAgent: routing topic %s to its bound device %s', topicId, topicPinnedDeviceId);
      }

      // Re-assert the share restriction after topic overrides are applied: a
      // topic pin can switch the run to another heterogeneous runtime or device.
      await assertShareHetero(model);

      // A builder conversation edits exactly one agent, stamped on the topic when
      // it was created. Continuations rebuilt from the durable operation (approval
      // or askUserQuestion resumes) arrive without `editingAgentId`; recover it
      // here so the run origin still carries the target instead of leaving the
      // builder tools with nothing to write to.
      if (appContext?.scope === 'agent_builder' && !editingAgentId) {
        editingAgentId = existingTopic?.metadata?.editingAgentId ?? undefined;
        log('execAgent: recovered editingAgentId=%s from topic %s', editingAgentId, topicId);
      }
    }
  } catch (error) {
    topicStage.fail(error);
    throw error;
  } finally {
    topicStage.end();
  }

  if (heterogeneousProvider) {
    // A new topic has no pins, yet a native Task model still replaces the
    // agent's model. Carry it in the pin so dispatch and its receipt both read
    // this one resolved result.
    if (nativeModelOverride && !pinnedHeterogeneousTopicModel?.model) {
      pinnedHeterogeneousTopicModel = {
        ...pinnedHeterogeneousTopicModel,
        model: nativeModelOverride,
        provider: nativeProviderOverride ?? heterogeneousProvider.type,
      };
    }
    if (pinnedHeterogeneousTopicModel) {
      pinnedHeterogeneousTopicSources = {
        effort: 'topic',
        model: nativeModelOverride ? (operationTaskId ? 'task' : undefined) : 'topic',
        speed: 'topic',
      };
    }
  }

  await throwIfExecutionAborted('topic setup');

  // Resolve device-tool access ONCE per turn, BEFORE the hetero early exit β€”
  // hetero dispatch routes the whole run to a user machine, so it must honour
  // the same policy as native device tools. Discord-only flows (no
  // botContext) keep the legacy first-party allow path; an external bot
  // sender returns canUseDevice=false and reason='bot-external-sender',
  // which degrades device-capable targets (hetero β†’ sandbox, native β†’ plain
  // chat) and stops the device list from leaking into the LLM context.
  const { canUseDevice, reason: deviceAccessReason } = resolveDeviceAccessPolicy({
    botContext,
    shareVisitor: shareGate ? { canUseDevice: shareGate.canUseDevice } : undefined,
  });
  log(
    'execAgent: device access policy β†’ canUseDevice=%s, reason=%s, hasBotContext=%s',
    canUseDevice,
    deviceAccessReason,
    !!botContext,
  );

  // Hetero detection: prefer agencyConfig.heterogeneousProvider.type (set by
  // the UI), fall back to the legacy `model` field for backwards compatibility
  // (shared with the inbox write guard via `isHeterogeneousAgentModelId`).
  const heteroProviderType = agentConfig.agencyConfig?.heterogeneousProvider?.type;
  const isHeteroAgent = !!heteroProviderType || isHeterogeneousAgentModelId(model);
  const heteroType = (heteroProviderType ?? model) as HeterogeneousAgentType;

  // ── Shared turn setup (runs for BOTH hetero and normal agents) ──────────
  const requestTriggerMetadata = buildUserTurnMetadata({
    agentSender,
    appContext,
    botSender,
    composerMetadata: userMessage?.metadata,
    externalOrigin,
    hasMentionedAgents,
    selectedSkillIds,
    selectedToolIds,
    steer,
    trigger,
  });

  // Attachment ingestion: raw bot/IM `files` β†’ S3, pre-uploaded
  // `attachedFileIds` β†’ signed URLs + classification.
  // Raw bot/IM uploads are parsed here, on the send path β€” a PDF can hold
  // this stage for seconds, which is why it gets its own span.
  const runAttachments = await traceTurnStage('attachments', async (span) => {
    const resolved = await resolveRunAttachments(deps, {
      attachedFileIds,
      fileAccessScope: shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,
      files,
      throwIfAborted: throwIfExecutionAborted,
    });
    span.setAttribute('lobehub.turn_setup.raw_file_count', files?.length ?? 0);
    span.setAttribute('lobehub.turn_setup.attached_file_count', attachedFileIds?.length ?? 0);
    return resolved;
  });

  await throwIfExecutionAborted('message creation');

  // Persist the user turn. `selfMessageIds` lets the normal-path history loader
  // exclude this freshly-created turn β€” history must be the PRIOR turns only,
  // otherwise the new prompt is double-counted in the LLM context.
  const { assistantMessageRecord, selfMessageIds, userMessageRecord } = await traceTurnStage(
    'messages',
    async () => {
      const selfMessageIds = new Set<string>();
      // Anchor the new user turn on the selected branch's tail (see
      // `createUserTurnAnchor` for why it is never left undefined).
      const anchor = createUserTurnAnchor(deps.messageModel, {
        allowShareVisitor: !!shareGate,
        clientParentId: clientIds?.userMessageParentId,
        groupId: appContext?.groupId ?? undefined,
        sessionId: appContext?.sessionId,
        threadId: appContext?.threadId ?? null,
        topicId,
      });
      const resolveParentId = async () => {
        if (runFromHistory) return undefined;
        if (parentMessageId) return parentMessageId;
        // A thread created for THIS turn is empty, so there is no spine head to
        // anchor on. Its branch point is the source message β€” the same anchor the
        // non-gateway path keeps for a brand-new thread. Without it the first turn
        // persists as a second root and the renderer's parentId walk emits it out
        // of order.
        if (createdThreadId) return appContext?.newThread?.sourceMessageId;

        return anchor.resolveParentId();
      };
      const userMessageParentId = await resolveParentId();
      const userMessageParams = {
        agentId: conversationAgentId,
        content: prompt,
        // Rich text as the composer authored it, like a client-runtime send stores.
        editorData: userMessage?.editorData,
        files: runAttachments.fileIds,
        // Group reads filter on messages.groupId (MessageModel.query group
        // branch), so a group turn must stamp groupId or the message never
        // shows when the topic is reopened (group topic sidebar + ownership fix).
        groupId: appContext?.groupId ?? undefined,
        metadata: requestTriggerMetadata,
        parentId: userMessageParentId,
        role: 'user' as const,
        threadId: appContext?.threadId ?? undefined,
        topicId,
      };
      // Share-visitor runs must reserve the `maxMessagesPerVisitor` slot and
      // insert the user message in ONE locked transaction β€” see
      // `reserveShareVisitorTurn`'s JSDoc for the race this closes. Non-share
      // runs (no per-visitor cap) keep the plain unlocked insert.
      const userMessageRecord = runFromHistory
        ? undefined
        : shareGate
          ? await reserveShareVisitorTurn(
              {
                agentId: shareGate.agentId,
                db: deps.db,
                expectedShareId: shareGate.shareId,
                ownerId: deps.userId,
                visitorUserId: shareGate.visitorUserId,
                workspaceId: deps.workspaceId,
              },
              userMessageParams,
              // The id the client's optimistic user row already renders under.
              clientIds?.userMessageId,
            )
          : await deps.messageModel.create(
              userMessageParams,
              // The id the client's optimistic user row already renders under.
              clientIds?.userMessageId,
            );
      if (userMessageRecord) {
        selfMessageIds.add(userMessageRecord.id);
        log('execAgent: created user message %s', userMessageRecord.id);
        await anchor.selectBranchOf(userMessageRecord);
      }

      // Snapshot the author's group orchestration role onto the assistant message
      // so the role survives the server round-trip (gateway step_start snapshot /
      // message.getMessages). Without this the client's optimistic isSupervisor flag
      // is lost on refetch and the supervisor renders as a generic assistant.
      // The persisted message `role` stays 'assistant' β€” only metadata carries the
      // orchestration role, keeping the data training-friendly.
      const orchestrationMetadata = appContext?.orchestrationRole
        ? {
            ...(appContext.orchestrationRole === 'supervisor' ? { isSupervisor: true } : {}),
            orchestrationRole: appContext.orchestrationRole,
          }
        : undefined;

      // Assistant placeholder (shows the spinner in the UI). A hetero run seeds
      // ONLY the provider β€” the CLI reports the real model later via `stream_start`
      // / `turn_metadata` (backfilled by HeterogeneousPersistenceHandler), and
      // seeding the agent's chat model would leak it into the model tag. A normal
      // run seeds model + provider as usual.
      const assistantParentId = userMessageRecord?.id ?? batchApprovalAnchorId ?? parentMessageId;
      const existingContinuationAssistant = continuationAssistantId
        ? await deps.messageModel.findById(continuationAssistantId)
        : undefined;

      if (
        existingContinuationAssistant &&
        (existingContinuationAssistant.role !== 'assistant' ||
          existingContinuationAssistant.topicId !== topicId ||
          (existingContinuationAssistant.threadId ?? undefined) !==
            (appContext?.threadId ?? undefined) ||
          (existingContinuationAssistant.parentId ?? undefined) !== assistantParentId ||
          existingContinuationAssistant.agentId !== assistantAgentId)
      ) {
        throw new Error(
          `Intervention continuation assistant identity conflict: ${continuationAssistantId}`,
        );
      }

      const assistantMessageRecord =
        existingContinuationAssistant ??
        (await deps.messageModel.create(
          {
            agentId: assistantAgentId,
            content: LOADING_FLAT,
            // Stamp groupId so the assistant turn is visible in the group read path
            // (MessageModel.query filters group chats by messages.groupId).
            groupId: appContext?.groupId ?? undefined,
            metadata: orchestrationMetadata,
            model: isHeteroAgent ? undefined : model,
            // Chain onto the user turn we just persisted; `parentMessageId` is the
            // anchor only on a resume, where no user message is created. A batch
            // approval overrides it with the assistant that emitted the batch β€” the
            // previous LLM call β€” so the spine stays one node per call and never
            // depends on which of the batch's tool rows the client sent as anchor.
            parentId: assistantParentId,
            provider: isHeteroAgent ? heteroType : provider,
            role: 'assistant',
            threadId: appContext?.threadId ?? undefined,
            topicId,
          },
          // Generic intervention continuations use a stable placeholder so a
          // crash after this insert but before operation-state creation can
          // safely re-enter without creating a second assistant turn.
          continuationAssistantId ?? clientIds?.assistantMessageId,
        ));
      selfMessageIds.add(assistantMessageRecord.id);
      log('execAgent: created assistant message %s', assistantMessageRecord.id);
      return { assistantMessageRecord, selfMessageIds, userMessageRecord };
    },
  );

  // Agent Signal is a governance side-channel (feedback / self-iteration). It
  // only applies to the server-side LLM pipeline, so it is intentionally NOT
  // enqueued for hetero runs (which hand off to an external CLI). Skip when this
  // invocation is itself an Agent Signal background run to avoid recursion.
  //
  // Share-visitor fail-closed gate β€” never enqueue this event for a
  // share-visitor turn. `enqueueAgentSignalSourceEvent` is always called with
  // `userId: deps.userId`, which is the share CREATOR (this service is
  // instantiated with `share.ownerId` for every visitor run β€” see
  // `shareChat.ts`), never `shareGate.visitorUserId`. The `agent.user.message`
  // event it produces feeds policies that can reach the `userMemory` action
  // and WRITE to the creator's memory. `allowReadMemory` only grants READING
  // the creator's memory through the visible memory tool, so this gate must
  // never be conditional on it: any share configuration would otherwise let a
  // link visitor mutate the creator's account via this out-of-band channel.
  //
  // There is no per-agent gate: every agent feeds this channel, and the user's
  // Labs β†’ Self-evolving switch is checked inside the enqueue.
  if (
    userMessageRecord &&
    !isHeteroAgent &&
    !shareGate &&
    !shouldSuppressSignal({ appContext, slug: agentSlug ?? undefined })
  ) {
    void enqueueAgentSignalSourceEvent(
      {
        payload: {
          agentId: resolvedAgentId,
          // Lets the feedback classifier skip a first message: nothing came before
          // it in the topic, so it cannot be feedback on an earlier reply.
          ...(!userMessageRecord.parentId && !appContext?.threadId
            ? { isConversationRoot: true }
            : {}),
          message: prompt,
          messageId: userMessageRecord.id,
          threadId: appContext?.threadId ?? undefined,
          topicId,
          trigger,
        },
        sourceId: userMessageRecord.id,
        sourceType: 'agent.user.message',
      },
      {
        agentId: resolvedAgentId,
        userId: deps.userId,
      },
    ).catch((error) => {
      log('execAgent: failed to enqueue user message Agent Signal source event: %O', error);
    });
  }

  return {
    assistantMessageId: assistantMessageRecord.id,
    canUseDevice,
    deviceAccessReason,
    editingAgentId,
    effectiveRequestedDeviceId,
    heteroType,
    heterogeneousProvider,
    isFixedDeviceTarget,
    isHeteroAgent,
    model,
    pinnedHeterogeneousTopicModel,
    pinnedHeterogeneousTopicSources,
    projectId: turnProjectId,
    provider,
    requestedDeviceId: resolvedRequestedDeviceId,
    requestTriggerMetadata,
    runAttachments,
    selfMessageIds,
    topicBoundDeviceId,
    topicEditingGroupId,
    topicId,
    userMessageId: userMessageRecord?.id ?? persistedUserMessageId,
  };
};