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.

27.9 KB
Raw Blame
import type {
  AnalyzeMediaParams,
  CallSubAgentParams,
  CancelSubAgentParams,
  CancelSubAgentState,
  MediaFileItem,
  MediaSourceMessage,
  VentParams,
  VentState,
} from '@lobechat/builtin-tool-lobe-agent';
import {
  buildAnalyzeMediaContent,
  buildBackgroundSubAgentReceipt,
  buildSteeredSubAgentReceipt,
  createMediaFileItemsFromMessage,
  createUrlMediaFileItems,
  formatMediaUrlValidationError,
  hasAnalyzableMediaFiles,
  LobeAgentIdentifier,
  normalizeAnalyzeMediaInput,
  selectMediaFileItems,
  validateMediaUrls,
} from '@lobechat/builtin-tool-lobe-agent';
import { PlanExecutionRuntime } from '@lobechat/builtin-tool-lobe-agent/planRuntime';
import { UserInteractionExecutionRuntime } from '@lobechat/builtin-tool-user-interaction/executionRuntime';
import type { LobeChatDatabase } from '@lobechat/database';
import type { ChatStreamPayload } from '@lobechat/model-runtime';
import { consumeStreamUntilDone } from '@lobechat/model-runtime';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
import { ChatErrorType, RequestTrigger } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import { parseDataUri } from '@lobechat/utils/uriParser';

import { MessageModel } from '@/database/models/message';
import { toolsEnv } from '@/envs/tools';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { FileService } from '@/server/services/file';
import {
  createRedisVentLedger,
  createVentService,
  formatVentResultContent,
  type VentRuntimeService,
} from '@/server/services/vent';

import type { ToolExecutionContext } from '../types';
import { startBackgroundSubAgent } from './backgroundSubAgent';
import { normalizeMultimodalImageItems } from './lobeAgentImage';
import { createServerPlanRuntimeService } from './lobeAgentPlan';
import type { ServerRuntimeRegistration } from './types';

// The durable record of a vent is the persisted vent tool-call message itself.
// This shared service only validates input, assigns a stable id, and enforces
// the per-run cap. The cap lives in Redis because consecutive steps of one run
// may execute on different instances; created lazily so importing this module
// does not open a connection.
let sharedVentService: VentRuntimeService | undefined;
const getVentService = () => {
  if (!sharedVentService) {
    const redis = getAgentRuntimeRedisClient();
    sharedVentService = createVentService({
      ledger: redis ? createRedisVentLedger(redis) : undefined,
      nextToolCallId: () => nanoid(),
    });
  }
  return sharedVentService;
};

interface LobeAgentRuntimeContext {
  agentId?: string | null;
  /**
   * Visibility of the executing agent. Forwarded to the plan runtime so plan
   * documents inherit private-agent visibility.
   */
  agentVisibility?: 'private' | 'public' | null;
  groupId?: string | null;
  messageId: string;
  /** The current Agent Run (`agent_operations.id`). */
  operationId?: string;
  serverDB: LobeChatDatabase;
  threadId?: string | null;
  topicId?: string;
  userId: string;
  workspaceId?: string;
}

const buildError = (content: string, code: string): BuiltinServerRuntimeOutput => ({
  content,
  error: { code, message: content },
  success: false,
});

/**
 * Quota rejections from the configured multimodal provider. analyzeMedia always
 * runs on the platform-configured model, so a user chatting with their own API
 * key can still hit the LobeHub credit budget here.
 */
const CREDIT_ERROR_TYPES = new Set<string>([
  ChatErrorType.FreePlanLimit,
  ChatErrorType.InsufficientBudgetForModel,
  ChatErrorType.SubscriptionPlanLimit,
]);

const getCreditErrorType = (error: unknown): string | undefined => {
  if (!error || typeof error !== 'object') return;
  const errorType = (error as { errorType?: unknown }).errorType;

  return typeof errorType === 'string' && CREDIT_ERROR_TYPES.has(errorType) ? errorType : undefined;
};

/**
 * Structured rejection from the model gateway (e.g. `{ errorType: 403,
 * message: "Request blocked.", _responseBody: { provider, reason:
 * "not_onboarded" } }`). The raw message alone gives the agent nothing to act
 * on — the gateway's `reason` is the only actionable signal, and rethrowing
 * collapses the whole payload into that bare string before the tool result is
 * built. Surface it instead of letting the failure degrade to "Request
 * blocked." with no code, no cause, and no recovery path.
 */
const getGatewayRejection = (error: unknown): { content: string; code: string } | undefined => {
  if (!error || typeof error !== 'object') return;

  const raw = error as {
    _responseBody?: { provider?: unknown; reason?: unknown };
    errorType?: unknown;
    message?: unknown;
  };

  const errorType = typeof raw.errorType === 'number' ? raw.errorType : undefined;
  const provider =
    typeof raw._responseBody?.provider === 'string' ? raw._responseBody.provider : undefined;
  const reason =
    typeof raw._responseBody?.reason === 'string' ? raw._responseBody.reason : undefined;
  const message = typeof raw.message === 'string' ? raw.message : undefined;

  // Numeric error types are part of the generic model-runtime error contract
  // (429 rate limits, 4xx validation, provider-policy refusals), and
  // `normalizeChatMessageError` propagates `provider` (and other display
  // metadata) into every error body — so neither establishes a gateway-level
  // refusal on its own. `_responseBody.reason` is the gateway-specific marker:
  // require it before suppressing the throw, and keep ordinary structured
  // errors (including provider-only response bodies, e.g. a 429 rate limit)
  // transparent and retryable via the existing rethrow behavior.
  if (errorType === undefined || !reason) return;

  const parts = [
    `Media analysis was rejected by the platform model gateway (HTTP ${errorType}${provider ? `, provider: ${provider}` : ''}).`,
    `Gateway reason: ${reason}.`,
    message && message !== 'error' ? `Upstream message: ${message}.` : undefined,
    'This is an account/gateway-level refusal, not a content-policy verdict on the media. Do not retry blindly or treat the media as blocked content.',
  ].filter(Boolean);

  return {
    code: `GATEWAY_${reason.toUpperCase().replaceAll(/[^A-Z0-9]+/g, '_')}`,
    content: parts.join(' '),
  };
};

const BASE64_CONTENT_PATTERN = /^[A-Z\d+/]+={0,2}$/i;
const MAX_INLINE_IMAGE_PIXELS = 25_000_000;
/**
 * Decode inline images before the provider boundary. Protocol and header checks
 * are insufficient because a PNG can retain a valid signature while its pixel
 * chunks or CRCs are corrupted. Decode sequentially with an explicit pixel
 * ceiling to cap peak memory for highly compressed and multi-image calls.
 */
const findInvalidInlineImageIndexes = async (urls: string[]) => {
  const invalidIndexes: number[] = [];
  const hasInlineImages = urls.some((url) => /^data:image\//i.test(url));
  if (!hasInlineImages) return invalidIndexes;

  // Keep the native image dependency out of server bundles that never validate
  // inline images; the server runtime registry imports this module eagerly.
  const { default: sharp } = await import('sharp');

  for (const [index, url] of urls.entries()) {
    if (!/^data:image\//i.test(url)) continue;

    const { base64, type } = parseDataUri(url);
    if (
      type !== 'base64' ||
      !base64 ||
      !BASE64_CONTENT_PATTERN.test(base64) ||
      base64.length % 4 === 1
    ) {
      invalidIndexes.push(index + 1);
      continue;
    }

    try {
      const buffer = Buffer.from(base64, 'base64');
      await sharp(buffer, {
        failOn: 'error',
        limitInputPixels: MAX_INLINE_IMAGE_PIXELS,
      }).stats();
    } catch {
      invalidIndexes.push(index + 1);
    }
  }

  return invalidIndexes;
};

const getModelAbilities = async (model: string, provider: string) => {
  const { loadModels } = await import('@/business/client/model-bank/loadModels');
  const builtinModels = await loadModels();

  return (
    builtinModels.find((item) => item.id === model && item.providerId === provider) ??
    builtinModels.find((item) => item.id === model)
  )?.abilities;
};

interface ServerMediaSourceMessage extends MediaSourceMessage {
  agentId?: string | null;
  groupId?: string | null;
  sessionId?: string | null;
  threadId?: string | null;
  topicId?: string | null;
}

class LobeAgentExecutionRuntime {
  private agentId?: string | null;
  private db: LobeChatDatabase;
  private groupId?: string | null;
  private userId: string;
  private messageId: string;
  private operationId?: string;
  private threadId?: string | null;
  private topicId?: string;
  private planRuntime: PlanExecutionRuntime;
  private workspaceId?: string;
  // Reused from the standalone user-interaction tool. askUserQuestion is
  // human-intervention 'always', so the user's UI answer normally becomes the
  // tool result; this runtime is only the fallback executor.
  private interactionRuntime = new UserInteractionExecutionRuntime();

  constructor(context: LobeAgentRuntimeContext) {
    this.agentId = context.agentId;
    this.db = context.serverDB;
    this.groupId = context.groupId;
    this.messageId = context.messageId;
    this.operationId = context.operationId;
    this.threadId = context.threadId;
    this.topicId = context.topicId;
    this.userId = context.userId;
    this.workspaceId = context.workspaceId;
    this.planRuntime = new PlanExecutionRuntime(
      createServerPlanRuntimeService(
        context.serverDB,
        context.userId,
        context.workspaceId,
        context.agentVisibility,
      ),
    );
  }

  // ==================== Ask User Question ====================

  askUserQuestion = (params: unknown): Promise<BuiltinServerRuntimeOutput> =>
    this.interactionRuntime.askUserQuestion(params);

  // ==================== Plan / Todo (delegated to PlanExecutionRuntime) ====================

  /**
   * Todo APIs read their prior state from `ctx.currentTodos` (rebuilt from
   * message history by the runtime executors). Without it the runtime falls back
   * to the topic's plan document, which only exists once `createPlan` has run —
   * so a plain `createTodos` → `updateTodos` sequence would see an empty list,
   * drop every index-based operation, and answer "No operations applied.".
   */
  private planContext = (ctx?: ToolExecutionContext) => ({
    currentTodos: ctx?.currentTodos,
    messageId: this.messageId,
    topicId: this.topicId,
  });

  createPlan = (params: any, ctx?: ToolExecutionContext) =>
    this.planRuntime.createPlan(params, this.planContext(ctx));

  updatePlan = (params: any, ctx?: ToolExecutionContext) =>
    this.planRuntime.updatePlan(params, this.planContext(ctx));

  createTodos = (params: any, ctx?: ToolExecutionContext) =>
    this.planRuntime.createTodos(params, this.planContext(ctx));

  updateTodos = (params: any, ctx?: ToolExecutionContext) =>
    this.planRuntime.updateTodos(params, this.planContext(ctx));

  clearTodos = (params: any, ctx?: ToolExecutionContext) =>
    this.planRuntime.clearTodos(params, this.planContext(ctx));

  // ==================== Sub-agent (async suspend/resume) ====================

  /**
   * Fork a sub-agent as an independent async operation.
   *
   * Returns a `deferred` result instead of a tool_result: the agent runtime
   * parks the parent op (`waiting_for_async_tool`) until the sub-op finishes,
   * at which point the completion bridge backfills the placeholder tool message
   * and resumes the parent. The placeholder + child-op kickoff are handled by
   * the injected `ctx.subAgent` runner (which owns the parent message anchor).
   */
  callSubAgent = async (
    params: CallSubAgentParams,
    ctx: ToolExecutionContext,
  ): Promise<BuiltinServerRuntimeOutput> => {
    if (ctx.isSubAgent) {
      return buildError(
        'Sub-agent calls cannot be triggered from within another sub-agent.',
        'NESTED_SUB_AGENT_NOT_ALLOWED',
      );
    }

    if (!ctx.subAgent) {
      return buildError(
        'Sub-agent execution is not available in this runtime.',
        'SUB_AGENT_UNAVAILABLE',
      );
    }

    const { description, instruction, timeout } = params;
    if (!instruction || typeof instruction !== 'string') {
      return buildError('instruction is required.', 'INVALID_ARGUMENTS');
    }
    if (params.subAgentId !== undefined && typeof params.subAgentId !== 'string') {
      return buildError('subAgentId must be a string.', 'INVALID_ARGUMENTS');
    }
    // Models trained on strict function schemas (the GPT family) fill every
    // declared field, so "start a new sub-agent" arrives as `subAgentId: ""`
    // rather than an omitted key. Blank means new.
    const subAgentId = params.subAgentId?.trim() || undefined;
    const background = params.runInBackground === true;

    const runner = ctx.subAgent;
    const startRun = () =>
      runner.run({ background, description, instruction, subAgentId, timeout });

    let runResult: Awaited<ReturnType<typeof startRun>>;
    if (background) {
      const outcome = await startBackgroundSubAgent({
        continuesThreadId: subAgentId,
        db: this.db,
        groupId: this.groupId,
        retryHint: 'Call callSubAgent again without runInBackground to wait for the result.',
        start: startRun,
        threadId: this.threadId,
        topicId: this.topicId,
        userId: this.userId,
        workspaceId: this.workspaceId,
      });
      if ('refusal' in outcome) return buildError(outcome.refusal.message, outcome.refusal.code);
      runResult = outcome.result;
    } else {
      runResult = await startRun();
    }
    const { started, error, steered, threadId, subOperationId, toolMessageId } = runResult;

    // The child op failed to start — no completion bridge will ever fire to
    // backfill a placeholder, so we must NOT defer/park here. Return a normal
    // (non-deferred) tool error so the parent's LLM sees the failure and the
    // batch continues instead of hanging in `waiting_for_async_tool`.
    if (!started) {
      const action = subAgentId ? 'could not be continued' : 'failed to start';
      return buildError(
        error ? `Sub-agent ${action}: ${error}` : `Sub-agent ${action}.`,
        'SUB_AGENT_START_FAILED',
      );
    }

    // Steered a sub-agent that is still running: the instruction joins its next
    // step, and the running call reports the answer. Nothing to wait for here.
    if (steered) {
      return {
        content: buildSteeredSubAgentReceipt(threadId),
        state: { status: 'completed', steered: true, threadId },
        success: true,
        toolMessageId,
      };
    }

    // Detached: the receipt is the whole tool result and the parent keeps going.
    // It goes into the placeholder the runner created (it anchors the thread);
    // the answer reaches the parent later as its own message.
    if (background) {
      return {
        content: buildBackgroundSubAgentReceipt(threadId),
        success: true,
        toolMessageId,
      };
    }

    return {
      // No tool_result yet — the bridge fills this in when the sub-op completes.
      content: '',
      deferred: true,
      // `toolMessageId` rides along so the runtime's pause chunk can tell the
      // client which row to fetch; the client never sees it as tool state.
      state: { status: 'pending', subOperationId, threadId, toolMessageId },
      success: true,
    };
  };

  /**
   * Stop a running sub-agent this agent dispatched earlier in the conversation.
   * Cancelling it before it reports back keeps the stop from waking this agent
   * again with a "did not complete" result (see `cancelSubAgentThreadRun`).
   */
  cancelSubAgent = async (
    params: CancelSubAgentParams,
    ctx: ToolExecutionContext,
  ): Promise<BuiltinServerRuntimeOutput> => {
    if (ctx.isSubAgent) {
      return buildError(
        'Sub-agents cannot be cancelled from within another sub-agent.',
        'NESTED_SUB_AGENT_NOT_ALLOWED',
      );
    }
    if (!ctx.subAgent?.cancel) {
      return buildError(
        'Cancelling a sub-agent is not available in this runtime.',
        'SUB_AGENT_UNAVAILABLE',
      );
    }
    const subAgentId = typeof params.subAgentId === 'string' ? params.subAgentId.trim() : '';
    if (!subAgentId) {
      return buildError(
        'subAgentId is required: pass the id from the sub-agent\'s <sub_agent id="..." /> tag.',
        'INVALID_ARGUMENTS',
      );
    }

    const result = await ctx.subAgent.cancel({ subAgentId });

    if (result.status === 'failed') {
      return buildError(
        `Sub-agent "${subAgentId}" could not be cancelled: ${result.error ?? 'unknown error'}`,
        'SUB_AGENT_CANCEL_FAILED',
      );
    }

    const state: CancelSubAgentState = { status: result.status, threadId: result.threadId };
    if (result.status === 'not_running') {
      return {
        content: `Sub-agent "${subAgentId}" is not running, so there was nothing to cancel. If it already finished, its result is (or will be) delivered as usual.`,
        state,
        success: true,
      };
    }

    return {
      content: result.stopped
        ? `Sub-agent "${subAgentId}" cancelled and stopped. No result will be delivered for it. Its history is kept: to steer it, call callSubAgent with subAgentId "${subAgentId}" and a corrected instruction.`
        : `Sub-agent "${subAgentId}" cancelled. It is still finishing its current step and stops after it; no result will be delivered for it. Its history is kept: once it has stopped, call callSubAgent with subAgentId "${subAgentId}" and a corrected instruction to steer it.`,
      state,
      success: true,
    };
  };

  // ==================== Vent ====================

  vent = async (
    params: VentParams,
    context: { operationId?: string; toolCallId?: string } = {},
  ): Promise<BuiltinServerRuntimeOutput> => {
    if (!this.agentId || !this.userId || !this.topicId) {
      const state: VentState = { recorded: false, reason: 'missing_context' };
      return { content: formatVentResultContent(state), state, success: false };
    }

    try {
      const result = await getVentService().recordVent({
        agentId: this.agentId,
        input: params,
        topicId: this.topicId,
        userId: this.userId,
        ...(context.operationId ? { operationId: context.operationId } : {}),
        ...(context.toolCallId ? { toolCallId: context.toolCallId } : {}),
      });

      const state: VentState = {
        category: params.category,
        reason: result.reason ?? null,
        recorded: result.recorded,
        severity: params.severity,
        ventId: result.ventId ?? null,
      };

      return { content: formatVentResultContent(state), state, success: true };
    } catch (e) {
      const message = e instanceof Error ? e.message : 'Unknown vent error';
      const state: VentState = {
        category: params.category,
        reason: 'runtime_error',
        recorded: false,
        severity: params.severity,
      };
      return {
        content: `vent failed with error detail: ${message}`,
        error: { message },
        state,
        success: false,
      };
    }
  };

  private queryScopeMessages = (
    messageModel: MessageModel,
    sourceMessage: ServerMediaSourceMessage,
    postProcessUrl: (
      path: string | null,
      file: { fileType: string; id?: string | null },
    ) => Promise<string>,
  ) => {
    const topicId = this.topicId ?? sourceMessage.topicId ?? undefined;
    const threadId = sourceMessage.threadId ?? this.threadId ?? undefined;
    const groupId = sourceMessage.groupId ?? this.groupId ?? undefined;
    const agentId = sourceMessage.agentId ?? this.agentId ?? undefined;
    const sessionId = sourceMessage.sessionId ?? undefined;

    if (threadId) {
      return messageModel.query({ threadId, topicId }, { postProcessUrl });
    }

    if (groupId) {
      return messageModel.query({ groupId, topicId }, { postProcessUrl });
    }

    if (agentId) {
      return messageModel.query({ agentId, topicId }, { postProcessUrl });
    }

    if (sessionId) {
      return messageModel.query({ sessionId, topicId }, { postProcessUrl });
    }

    if (topicId) {
      return messageModel.query({ topicId }, { postProcessUrl });
    }

    return Promise.resolve([sourceMessage]);
  };

  analyzeMedia = async (params: AnalyzeMediaParams): Promise<BuiltinServerRuntimeOutput> => {
    const provider = toolsEnv.MULTIMODAL_UNDERSTANDING_PROVIDER;
    const model = toolsEnv.MULTIMODAL_UNDERSTANDING_MODEL;

    if (!provider || !model) {
      return buildError(
        'Multimodal understanding is not configured. Set MULTIMODAL_UNDERSTANDING_PROVIDER and MULTIMODAL_UNDERSTANDING_MODEL.',
        'MULTIMODAL_UNDERSTANDING_NOT_CONFIGURED',
      );
    }

    if (!params.question || typeof params.question !== 'string') {
      return buildError('question is required.', 'INVALID_ARGUMENTS');
    }

    const { requestedRefs, requestedUrls } = normalizeAnalyzeMediaInput(
      params as unknown as Record<PropertyKey, unknown>,
    );
    if (requestedRefs.length === 0 && requestedUrls.length === 0) {
      return buildError(
        'Either refs or urls is required and must include at least one media file ref or media URL.',
        'INVALID_ARGUMENTS',
      );
    }

    const urlValidation = validateMediaUrls(requestedUrls);
    const urlValidationError = formatMediaUrlValidationError(urlValidation);
    if (urlValidationError) {
      return buildError(urlValidationError, 'UNSUPPORTED_MEDIA_URLS');
    }

    const invalidInlineImageIndexes = await findInvalidInlineImageIndexes(urlValidation.validUrls);
    if (invalidInlineImageIndexes.length > 0) {
      return buildError(
        `Invalid inline image data at URL indexes: ${invalidInlineImageIndexes.join(', ')}.`,
        'INVALID_IMAGE_DATA',
      );
    }

    const selectedUrlItems = createUrlMediaFileItems(urlValidation.validUrls);
    let selectedRefItems: MediaFileItem[] = [];

    if (requestedRefs.length > 0) {
      const fileService = new FileService(this.db, this.userId, this.workspaceId);
      const messageModel = new MessageModel(this.db, this.userId, this.workspaceId);
      const postProcessUrl = (
        path: string | null,
        file: { fileType: string; id?: string | null },
      ) => fileService.getFileAccessUrl({ id: file.id, url: path });
      const [sourceMessage] = await messageModel.queryByIds([this.messageId], {
        postProcessUrl,
      });

      const mediaMessages = sourceMessage
        ? await this.queryScopeMessages(messageModel, sourceMessage, postProcessUrl)
        : [];
      const orderedMediaMessages = [
        ...(sourceMessage && hasAnalyzableMediaFiles(sourceMessage) ? [sourceMessage] : []),
        ...mediaMessages.filter(
          (message) => message.id !== sourceMessage?.id && hasAnalyzableMediaFiles(message),
        ),
      ];

      if (!sourceMessage) {
        return buildError(
          `Source message not found: ${this.messageId}`,
          'SOURCE_MESSAGE_NOT_FOUND',
        );
      }

      const mediaItems = orderedMediaMessages.flatMap((message) =>
        createMediaFileItemsFromMessage(message),
      );

      if (mediaItems.length === 0) {
        return buildError('No media files are attached to the current message.', 'NO_MEDIA_FILES');
      }

      const { availableRefs, invalidRefs, selected } = selectMediaFileItems(
        mediaItems,
        requestedRefs,
      );

      if (invalidRefs.length > 0) {
        return buildError(
          `Unknown media file refs: ${invalidRefs.join(', ')}. Available refs: ${availableRefs.join(', ')}.`,
          'UNKNOWN_MEDIA_FILE_REFS',
        );
      }

      selectedRefItems = selected;
    }

    const selectedItems = [...selectedRefItems, ...selectedUrlItems];

    if (selectedItems.length === 0) {
      return buildError('No media files selected.', 'NO_MEDIA_FILES_SELECTED');
    }

    const abilities = await getModelAbilities(model, provider);
    const hasAudios = selectedItems.some((item) => item.type === 'audio');
    const hasImages = selectedItems.some((item) => item.type === 'image');
    const hasVideos = selectedItems.some((item) => item.type === 'video');

    if (hasAudios && abilities?.audio === false) {
      return buildError(
        `Configured multimodal understanding model "${provider}/${model}" does not support audio understanding.`,
        'MULTIMODAL_MODEL_AUDIO_UNSUPPORTED',
      );
    }

    if (hasImages && abilities?.vision === false) {
      return buildError(
        `Configured multimodal understanding model "${provider}/${model}" does not support image vision.`,
        'MULTIMODAL_MODEL_IMAGE_UNSUPPORTED',
      );
    }

    if (hasVideos && abilities?.video === false) {
      return buildError(
        `Configured multimodal understanding model "${provider}/${model}" does not support video understanding.`,
        'MULTIMODAL_MODEL_VIDEO_UNSUPPORTED',
      );
    }

    let modelItems = selectedItems;
    if (hasImages) {
      try {
        modelItems = await normalizeMultimodalImageItems(
          selectedItems,
          toolsEnv.MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS,
        );
      } catch (error) {
        console.error('Failed to prepare images for multimodal understanding:', {
          name: error instanceof Error ? error.name : 'UnknownError',
        });
        return buildError(
          'Failed to prepare one or more images for the configured multimodal understanding model.',
          'MULTIMODAL_IMAGE_PREPARATION_FAILED',
        );
      }
    }

    let content = '';
    let usage: unknown;
    const runtime = await initModelRuntimeFromDB(this.db, this.userId, provider, this.workspaceId);
    const payload = {
      messages: [
        {
          content: buildAnalyzeMediaContent(modelItems, params.question),
          role: 'user' as const,
        },
      ],
      model,
      stream: false,
    } satisfies ChatStreamPayload;

    try {
      const response = await runtime.chat(payload, {
        callback: {
          onCompletion: (data) => {
            usage = data.usage;
          },
          onContentPart: (part) => {
            if (part.partType === 'text') content += part.content;
          },
          onText: (text) => {
            content += text;
          },
        },
        metadata: {
          trigger: RequestTrigger.MultimodalAnalysis,
        },
      });

      await consumeStreamUntilDone(response);
    } catch (error) {
      const creditErrorType = getCreditErrorType(error);
      if (!creditErrorType) {
        const rejection = getGatewayRejection(error);
        if (!rejection) throw error;

        return buildError(rejection.content, rejection.code);
      }

      return buildError(
        `Media analysis could not run: it uses the platform model "${provider}/${model}", which is billed to the user's LobeHub balance, and that balance is exhausted (${creditErrorType}). ` +
          "The user's own API key for the chat model is not used by this tool, so retrying will not help. " +
          'Tell the user to top up or upgrade their LobeHub plan, or to switch the conversation to a vision-capable model on their own API key.',
        creditErrorType,
      );
    }

    return {
      content: content.trim(),
      state: {
        files: selectedItems.map(({ ref, id, type, name }) => ({ id, name, ref, type })),
        model,
        provider,
        trigger: RequestTrigger.MultimodalAnalysis,
        usage,
      },
      success: true,
    };
  };
}

export const lobeAgentRuntime: ServerRuntimeRegistration = {
  factory: (context) => {
    if (!context.serverDB) {
      throw new Error('serverDB is required for LobeAgent execution');
    }
    if (!context.userId) {
      throw new Error('userId is required for LobeAgent execution');
    }
    if (!context.messageId) {
      throw new Error('messageId is required for LobeAgent execution');
    }

    return new LobeAgentExecutionRuntime({
      agentId: context.agentId,
      agentVisibility: context.agentVisibility,
      groupId: context.groupId,
      messageId: context.messageId,
      operationId: context.operationId,
      serverDB: context.serverDB,
      threadId: context.threadId,
      topicId: context.topicId,
      userId: context.userId,
      workspaceId: context.workspaceId,
    });
  },
  identifier: LobeAgentIdentifier,
};