π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor: extract server call llm context build (#16950)
Arvin Xuc41a441d0371
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsnew file mode 100644index 00000000000..b57ccdb9b45--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -0,0 +1,566 @@+import type { AgentState, CallLLMPayload } from '@lobechat/agent-runtime';+import {+ type ComposioServiceSummary,+ type CredSummary,+ excludeDisabledComposioServices,+ generateComposioServicesList,+ generateCredsList,+ resolveAvailableComposioServices,+} from '@lobechat/builtin-tool-creds';+import { builtinTools } from '@lobechat/builtin-tools';+import { COMPOSIO_APP_TYPES } from '@lobechat/const';+import type {+ AgentBuilderContext,+ AgentContextDocument,+ AgentGroupConfig,+ OfficialToolItem,+ OnboardingContext,+} from '@lobechat/context-engine';+import { resolveTopicReferences } from '@lobechat/context-engine';+import type { ChatStreamPayload } from '@lobechat/model-runtime';+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import {+ buildContextEngineeringAttributes,+ CONTEXT_ENGINEERING_SPAN_NAME,+ tracer as agentRuntimeTracer,+} from '@lobechat/observability-otel/modules/agent-runtime';+import { getActivePluginIds, getDisabledPluginIds } from '@lobechat/types';++import { composioEnv } from '@/config/composio';+import { AgentModel } from '@/database/models/agent';+import { FileModel } from '@/database/models/file';+import { MessageModel as MessageModelClass } from '@/database/models/message';+import { PluginModel } from '@/database/models/plugin';+import { TopicModel } from '@/database/models/topic';+import { UserModel } from '@/database/models/user';+import { UserPersonaModel } from '@/database/models/userMemory/persona';+import { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';+import { AgentDocumentsService } from '@/server/services/agentDocuments';+import { MarketService } from '@/server/services/market';+import { OnboardingService } from '@/server/services/onboarding';+import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';++import type { RuntimeExecutorContext } from '../context';+import { buildPostProcessUrl, log, resolveRuntimeHistoryCount } from '../executorHelpers';+import {+ resolveServerCallLlmContextHints,+ type ServerCallLlmContextHints,+} from './serverCallLlmContextHints';+import type { ServerCallLlmTooling } from './serverCallLlmTooling';++interface BuildServerCallLlmContextInput {+ ctx: RuntimeExecutorContext;+ llmPayload: CallLLMPayload;+ model: string;+ provider: string;+ state: AgentState;+ tooling: ServerCallLlmTooling;+}++export interface ServerCallLlmContextBuildResult {+ preserveThinkingForPayload?: boolean;+ processedMessages: ChatStreamPayload['messages'];+ resolvedExtendParams?: ServerCallLlmContextHints['resolvedExtendParams'];+ shouldReplayAssistantReasoning: boolean;+}++export const buildServerCallLlmContext = async ({+ ctx,+ llmPayload,+ model,+ provider,+ state,+ tooling,+}: BuildServerCallLlmContextInput): Promise<ServerCallLlmContextBuildResult> => {+ const agentConfig = ctx.agentConfig;+ if (!agentConfig) {+ return {+ processedMessages: llmPayload.messages as ChatStreamPayload['messages'],+ shouldReplayAssistantReasoning: false,+ };+ }++ const { operationId, stepIndex } = ctx;+ const { resolved, resolvedSkills, toolDiscoveryConfig } = tooling;+ const contextHints = await resolveServerCallLlmContextHints({+ ctx,+ llmPayload,+ model,+ provider,+ });+ const {+ capabilities,+ messagesForContext,+ modelDisplayName,+ modelKnowledgeCutoff,+ preserveThinkingForPayload,+ resolvedExtendParams,+ shouldReplayAssistantReasoning,+ } = contextHints;++ // Extract <refer_topic> tags from messages and fetch summaries.+ // Skip if messages already contain injected topic_reference_context+ // (e.g., from client-side contextEngineering preprocessing) to avoid double injection.+ let topicReferences;+ const alreadyHasTopicRefs = (messagesForContext as Array<{ content: string | unknown }>).some(+ (message) =>+ typeof message.content === 'string' && message.content.includes('topic_reference_context'),+ );++ if (!alreadyHasTopicRefs && ctx.serverDB && ctx.userId) {+ const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const messageModel = new MessageModelClass(ctx.serverDB, ctx.userId, ctx.workspaceId);+ topicReferences = await resolveTopicReferences(+ messagesForContext as Array<{ content: string | unknown }>,+ async (topicId) => topicModel.findById(topicId),+ async (topicId) => {+ const topic = await topicModel.findById(topicId);+ return messageModel.query(+ {+ agentId: topic?.agentId ?? undefined,+ groupId: topic?.groupId ?? undefined,+ topicId,+ },+ { postProcessUrl: buildPostProcessUrl(ctx) },+ );+ },+ );+ }++ // Fetch agent documents for context injection.+ let agentDocuments: AgentContextDocument[] | undefined;+ const agentId = state.metadata?.agentId;+ if (agentId && ctx.serverDB && ctx.userId) {+ try {+ const agentDocService = new AgentDocumentsService(+ ctx.serverDB,+ ctx.userId,+ state.metadata?.workspaceId ?? ctx.workspaceId,+ );+ const docs = await agentDocService.getAgentContextDocuments(agentId);+ if (docs.length > 0) {+ agentDocuments = toAgentContextDocuments(docs);+ log('Resolved %d agent documents for agent %s', agentDocuments.length, agentId);+ }+ } catch (error) {+ log('Failed to resolve agent documents for agent %s: %O', agentId, error);+ }+ }++ // Detect onboarding agent and build context injection.+ let onboardingContext: OnboardingContext | undefined;+ const isOnboardingAgent =+ agentConfig?.slug === 'web-onboarding' ||+ resolved.enabledToolIds.includes('lobe-web-onboarding');+ const alreadyHasOnboardingContext = (+ messagesForContext as Array<{ content: string | unknown }>+ ).some((message) => {+ if (typeof message.content !== 'string') return false;++ return (+ message.content.includes('<onboarding_context>') ||+ message.content.includes('<current_soul_document>') ||+ message.content.includes('<current_user_persona>')+ );+ });++ if (isOnboardingAgent && !alreadyHasOnboardingContext && ctx.serverDB && ctx.userId) {+ try {+ const { formatWebOnboardingStateMessage } =+ await import('@lobechat/builtin-tool-web-onboarding/utils');+ const onboardingService = new OnboardingService(ctx.serverDB, ctx.userId);+ const docService = new AgentDocumentsService(+ ctx.serverDB,+ ctx.userId,+ state.metadata?.workspaceId ?? ctx.workspaceId,+ );+ const personaModel = new UserPersonaModel(ctx.serverDB, ctx.userId);++ const [onboardingState, soulDoc, persona, userInfo] = await Promise.all([+ onboardingService.getState(),+ onboardingService+ .getInboxAgentId()+ .then((inboxAgentId) =>+ inboxAgentId ? docService.getDocumentByFilename(inboxAgentId, 'SOUL.md') : null,+ )+ .catch((error) => {+ log('Failed to fetch SOUL.md for onboarding context: %O', error);+ return null;+ }),+ personaModel.getLatestPersonaDocument().catch((error) => {+ log('Failed to fetch user persona for onboarding context: %O', error);+ return null;+ }),+ onboardingService.getInitialUserInfo().catch((error) => {+ log('Failed to fetch initial user info for onboarding context: %O', error);+ return undefined;+ }),+ ]);++ onboardingContext = {+ discoveryUserMessageCount: onboardingState.discoveryUserMessageCount,+ personaContent: persona?.persona ?? null,+ phaseGuidance: formatWebOnboardingStateMessage(onboardingState),+ remainingDiscoveryExchanges: onboardingState.remainingDiscoveryExchanges,+ soulContent: soulDoc?.content ?? null,+ userInfo,+ };+ log('Built onboarding context for agent %s, phase: %s', agentId, onboardingState.phase);+ } catch (error) {+ log('Failed to build onboarding context: %O', error);+ }+ }++ // Build additional placeholder variables for the lobehub builtin skill+ // (`packages/builtin-skills/src/lobehub/content.ts`) so it can render+ // `{{agent_id}}` / `{{agent_title}}` / `{{topic_id}}` etc. into the+ // model's prompt without needing a separate context injector.+ const lobehubSkillAgentId = state.metadata?.agentId;+ const lobehubSkillTopicId = state.metadata?.topicId;+ const lobehubSkillAgentMeta = state.metadata?.agentConfig as+ { description?: string | null; title?: string | null } | undefined;++ let lobehubSkillTopicTitle = '';+ if (lobehubSkillTopicId && ctx.serverDB && ctx.userId) {+ try {+ const topicModelForLobehub = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const topicRecord = await topicModelForLobehub.findById(lobehubSkillTopicId);+ lobehubSkillTopicTitle = topicRecord?.title ?? '';+ } catch (error) {+ log('Failed to load topic title for lobehub skill placeholders: %O', error);+ }+ }++ const lobehubSkillVariables: Record<string, string> = {+ agent_description: lobehubSkillAgentMeta?.description ?? '',+ agent_id: lobehubSkillAgentId ?? '',+ agent_title: lobehubSkillAgentMeta?.title ?? '',+ topic_id: lobehubSkillTopicId ?? '',+ topic_title: lobehubSkillTopicTitle,+ };++ // Tool-specific template variable resolution. The client-side+ // contextEngineering.ts resolves these via Zustand stores and lambdaClient.+ // In execAgent (server/bot) mode we must fetch from DB directly.+ let serverUsername = '';+ let serverLanguage = '';+ if (ctx.serverDB && ctx.userId) {+ try {+ const userInfo = await UserModel.getInfoForAIGeneration(ctx.serverDB, ctx.userId);+ serverUsername = userInfo.userName;+ serverLanguage = userInfo.responseLanguage;+ } catch (error) {+ log('Failed to fetch user info for {{username}}/{{language}} substitution: %O', error);+ }+ }++ const sandboxEnabled = String(resolved.enabledToolIds.includes('lobe-cloud-sandbox'));+ let sandboxUploadedFiles = '';+ if (sandboxEnabled === 'true' && ctx.serverDB && ctx.userId && lobehubSkillTopicId) {+ try {+ const { formatUploadedFilesPrompt } = await import('@lobechat/builtin-tool-cloud-sandbox');+ const fileModel = new FileModel(ctx.serverDB, ctx.userId);+ const uploadedFiles = await fileModel.findFilesToInitInSandbox(lobehubSkillTopicId);+ sandboxUploadedFiles = formatUploadedFilesPrompt(uploadedFiles);+ } catch (error) {+ log('Failed to resolve files for {{sandbox_uploaded_files}} substitution: %O', error);+ }+ }++ const sessionDate = new Intl.DateTimeFormat('en-US', {+ day: 'numeric',+ month: 'long',+ timeZone: ctx.userTimezone || 'UTC',+ weekday: 'long',+ year: 'numeric',+ }).format(new Date());++ const memoryEffort = String(+ (state.metadata?.agentConfig as any)?.chatConfig?.memory?.effort ?? '',+ );++ let credsListStr = '';+ if (ctx.userId) {+ try {+ const marketService = new MarketService({ userInfo: { userId: ctx.userId } });+ // Inside a workspace, the agent must only see the workspace's shared+ // organization credentials β personal creds are not visible here (LOBE-10978).+ const credsResult = ctx.workspaceId+ ? await marketService.market.organizations.creds({ workspaceId: ctx.workspaceId }).list()+ : await marketService.market.creds.list();+ const userCreds = (credsResult as any)?.data ?? [];+ credsListStr = generateCredsList(+ userCreds.map((cred: any): CredSummary => ({+ description: cred.description,+ key: cred.key,+ name: cred.name,+ ownerDisplayName: cred.ownerDisplayName,+ ownerType: cred.ownerType,+ type: cred.type,+ })),+ );+ log('Fetched %d creds for {{CREDS_LIST}} substitution', userCreds.length);+ } catch (error) {+ log('Failed to fetch creds for {{CREDS_LIST}} substitution: %O', error);+ }+ }++ let composioServicesListStr = '';+ if (ctx.serverDB && ctx.userId && !!composioEnv.COMPOSIO_API_KEY) {+ try {+ const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const allPlugins = await pluginModel.query();+ const validComposioIds = new Set(COMPOSIO_APP_TYPES.map((tool) => tool.identifier));+ const connectedIds = new Set(+ allPlugins+ .filter(+ (plugin) =>+ validComposioIds.has(plugin.identifier) &&+ (plugin.customParams as any)?.composio?.status === 'ACTIVE',+ )+ .map((plugin) => plugin.identifier),+ );+ // Disabled services are dropped from both lists β not surfaced as+ // "connected, use directly" nor as "available to connect".+ let disabledIdSet = new Set<string>();+ if (agentId) {+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const agentConfig = await agentModel.getAgentConfigById(agentId);+ disabledIdSet = new Set(getDisabledPluginIds(agentConfig?.plugins ?? undefined));+ }+ const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(+ COMPOSIO_APP_TYPES.filter((tool) => connectedIds.has(tool.identifier)),+ disabledIdSet,+ ).map((tool) => ({ identifier: tool.identifier, name: tool.label }));+ const available = resolveAvailableComposioServices(+ COMPOSIO_APP_TYPES,+ connectedIds,+ disabledIdSet,+ );+ composioServicesListStr = generateComposioServicesList(connected, available);+ log(+ 'Fetched Composio services for {{COMPOSIO_SERVICES_LIST}}: connected=%d, available=%d',+ connected.length,+ available.length,+ );+ } catch (error) {+ log(+ 'Failed to fetch Composio services for {{COMPOSIO_SERVICES_LIST}} substitution: %O',+ error,+ );+ }+ }++ let agentBuilderContext: AgentBuilderContext | undefined;+ const editingAgentId = state.metadata?.editingAgentId;+ if (editingAgentId && ctx.serverDB && ctx.userId) {+ try {+ const editingAgentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const editingConfig = (await editingAgentModel.getAgentConfigById(editingAgentId)) as Record<+ string,+ any+ > | null;+ if (editingConfig) {+ const enabledPlugins: string[] = getActivePluginIds(+ Array.isArray(editingConfig.plugins) ? editingConfig.plugins : undefined,+ );+ const composioIdentifiers = new Set(COMPOSIO_APP_TYPES.map((tool) => tool.identifier));+ const officialTools: OfficialToolItem[] = [];++ for (const tool of builtinTools) {+ if (tool.hidden) continue;+ if (composioIdentifiers.has(tool.identifier)) continue;+ officialTools.push({+ description: tool.manifest?.meta?.description,+ enabled: enabledPlugins.includes(tool.identifier),+ identifier: tool.identifier,+ installed: true,+ name: tool.manifest?.meta?.title || tool.identifier,+ type: 'builtin',+ });+ }++ if (composioEnv.COMPOSIO_API_KEY) {+ try {+ const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const allPlugins = await pluginModel.query();+ const connectedComposioIds = new Set(+ allPlugins+ .filter(+ (plugin) =>+ composioIdentifiers.has(plugin.identifier) &&+ (plugin.customParams as any)?.composio?.status === 'ACTIVE',+ )+ .map((plugin) => plugin.identifier),+ );+ for (const tool of COMPOSIO_APP_TYPES) {+ officialTools.push({+ description: `LobeHub Mcp Server: ${tool.label}`,+ enabled: enabledPlugins.includes(tool.identifier),+ identifier: tool.identifier,+ installed: connectedComposioIds.has(tool.identifier),+ name: tool.label,+ type: 'composio',+ });+ }+ } catch (composioError) {+ log('Failed to load Composio status for agentBuilderContext: %O', composioError);+ }+ }++ agentBuilderContext = {+ config: {+ chatConfig: editingConfig.chatConfig ?? undefined,+ model: editingConfig.model ?? undefined,+ openingMessage: editingConfig.openingMessage ?? undefined,+ openingQuestions: editingConfig.openingQuestions ?? undefined,+ params: editingConfig.params ?? undefined,+ plugins: enabledPlugins,+ provider: editingConfig.provider ?? undefined,+ systemRole: editingConfig.systemRole ?? undefined,+ },+ meta: {+ avatar: editingConfig.avatar ?? undefined,+ backgroundColor: editingConfig.backgroundColor ?? undefined,+ description: editingConfig.description ?? undefined,+ tags: editingConfig.tags ?? undefined,+ title: editingConfig.title ?? undefined,+ },+ ...(officialTools.length > 0 && { officialTools }),+ };+ }+ } catch (error) {+ log('Failed to build agentBuilderContext for editing agent %s: %O', editingAgentId, error);+ }+ }++ const contextEngineInput = {+ agentDocuments,+ ...(agentBuilderContext && { agentBuilderContext }),+ agentGroup: state.metadata?.agentGroup as AgentGroupConfig | undefined,+ agentManagementContext: (state as any).initialContext?.initialContext?.mentionedAgents?.length+ ? {+ mentionedAgents: (state as any).initialContext.initialContext.mentionedAgents,+ }+ : undefined,+ additionalVariables: {+ ...state.metadata?.deviceSystemInfo,+ ...lobehubSkillVariables,+ COMPOSIO_SERVICES_LIST: composioServicesListStr,+ CREDS_LIST: credsListStr,+ language: serverLanguage,+ memory_effort: memoryEffort,+ sandbox_enabled: sandboxEnabled,+ sandbox_uploaded_files: sandboxUploadedFiles,+ session_date: sessionDate,+ username: serverUsername,+ },+ userTimezone: ctx.userTimezone,+ capabilities,+ botPlatformContext: ctx.botPlatformContext,+ discordContext: ctx.discordContext,+ enableHistoryCount: agentConfig.chatConfig?.enableHistoryCount ?? undefined,+ evalContext: ctx.evalContext,+ forceFinish: state.forceFinish,+ historyCount: resolveRuntimeHistoryCount(agentConfig.chatConfig?.historyCount),+ initialContext: (state as any).initialContext?.initialContext,+ knowledge: {+ fileContents: agentConfig.files+ ?.filter((file: { enabled?: boolean | null }) => file.enabled === true)+ .map((file: { content?: string | null; id?: string; name?: string }) => ({+ content: file.content ?? '',+ fileId: file.id ?? '',+ filename: file.name ?? '',+ })),+ knowledgeBases: agentConfig.knowledgeBases+ ?.filter((knowledgeBase: { enabled?: boolean | null }) => knowledgeBase.enabled === true)+ .map((knowledgeBase: { id?: string; name?: string }) => ({+ id: knowledgeBase.id ?? '',+ name: knowledgeBase.name ?? '',+ })),+ },+ messages: messagesForContext,+ model,+ modelDisplayName,+ modelKnowledgeCutoff,+ provider,+ systemRole: agentConfig.systemRole ?? undefined,+ toolDiscoveryConfig,+ toolsConfig: {+ manifests: Object.values(resolved.manifestMap),+ tools: resolved.enabledToolIds,+ },+ userMemory: state.metadata?.userMemory,+ ...(resolvedSkills?.enabledSkills?.length && {+ skillsConfig: { enabledSkills: resolvedSkills.enabledSkills },+ }),+ enableAgentMode: agentConfig.chatConfig?.enableAgentMode,+ ...(topicReferences && { topicReferences }),+ ...(onboardingContext && { onboardingContext }),+ };++ const processedMessages = await agentRuntimeTracer.startActiveSpan(+ CONTEXT_ENGINEERING_SPAN_NAME,+ {+ attributes: buildContextEngineeringAttributes({+ hasImages: (messagesForContext as Array<{ content?: unknown }>).some(+ (message) =>+ Array.isArray(message.content) &&+ (message.content as Array<{ type?: string }>).some(+ (part) => part?.type === 'image_url',+ ),+ ),+ historyCompressed:+ Array.isArray(messagesForContext) &&+ messagesForContext.some(+ (message: { role?: string }) => message?.role === 'compressedGroup',+ ),+ knowledgeCount:+ (contextEngineInput.knowledge?.knowledgeBases?.length ?? 0) ++ (contextEngineInput.knowledge?.fileContents?.length ?? 0),+ knowledgeInjected:+ (contextEngineInput.knowledge?.knowledgeBases?.length ?? 0) > 0 ||+ (contextEngineInput.knowledge?.fileContents?.length ?? 0) > 0,+ memoryInjected: Boolean(contextEngineInput.userMemory?.memories),+ messageCount: messagesForContext.length,+ operationId,+ stepIndex,+ systemRoleLength: contextEngineInput.systemRole?.length,+ toolCount: contextEngineInput.toolsConfig?.tools?.length ?? 0,+ }),+ },+ async (ceSpan) => {+ try {+ const result = await serverMessagesEngine(contextEngineInput);+ ceSpan.setAttribute('lobehub.context.message_count', result.length);+ return result;+ } catch (error) {+ ceSpan.recordException(error as Error);+ ceSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ throw error;+ } finally {+ ceSpan.end();+ }+ },+ );++ const {+ messages: _inputMsgs,+ toolsConfig: _toolsConfig,+ ...contextEngineInputLite+ } = contextEngineInput;+ ctx.tracingContextEngine?.(+ { ...contextEngineInputLite, toolCount: _toolsConfig?.tools?.length ?? 0 },+ processedMessages,+ );++ return {+ preserveThinkingForPayload,+ processedMessages,+ resolvedExtendParams,+ shouldReplayAssistantReasoning,+ };+};diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.tsnew file mode 100644index 00000000000..6ade2402b7b--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts@@ -0,0 +1,181 @@+import { type CallLLMPayload, stripAssistantReasoningForReplay } from '@lobechat/agent-runtime';+import { BRANDING_PROVIDER } from '@lobechat/business-const';+import {+ applyModelExtendParams,+ isDeepSeekThinkingEligibleModel,+ isDeepSeekV4FamilyModel,+ isKimiAlwaysPreserveThinkingModel,+ type ModelExtendParams,+} from '@lobechat/model-runtime';+import type { UIChatMessage } from '@lobechat/types';+import { type ExtendParamsType, ModelProvider } from 'model-bank';++import { AiModelModel } from '@/database/models/aiModel';++import type { RuntimeExecutorContext } from '../context';+import { log } from '../executorHelpers';++interface ResolveServerCallLlmContextHintsInput {+ ctx: RuntimeExecutorContext;+ llmPayload: CallLLMPayload;+ model: string;+ provider: string;+}++export interface ServerCallLlmContextHints {+ capabilities: {+ isCanUseAudio: (model: string, provider: string) => boolean;+ isCanUseFC: (model: string, provider: string) => boolean;+ isCanUseVideo: (model: string, provider: string) => boolean;+ isCanUseVision: (model: string, provider: string) => boolean;+ };+ messagesForContext: UIChatMessage[];+ modelDisplayName?: string;+ modelKnowledgeCutoff?: string;+ preserveThinkingForPayload?: boolean;+ resolvedExtendParams?: ModelExtendParams;+ shouldReplayAssistantReasoning: boolean;+}++export const resolveServerCallLlmContextHints = async ({+ ctx,+ llmPayload,+ model,+ provider,+}: ResolveServerCallLlmContextHintsInput): Promise<ServerCallLlmContextHints> => {+ const agentConfig = ctx.agentConfig;+ const { loadModels } = await import('@/business/client/model-bank/loadModels');+ const builtinModels = await loadModels();++ const preserveThinkingConfigured =+ typeof agentConfig?.chatConfig?.preserveThinking === 'boolean'+ ? agentConfig.chatConfig.preserveThinking+ : undefined;+ const preserveThinkingRequested = preserveThinkingConfigured === true;++ const readExtendParams = (+ card: (typeof builtinModels)[number] | undefined,+ ): string[] | undefined =>+ card &&+ 'settings' in card &&+ card.settings &&+ typeof card.settings === 'object' &&+ 'extendParams' in card.settings+ ? (card.settings as { extendParams?: string[] }).extendParams+ : undefined;++ const modelCard = builtinModels.find(+ (item) =>+ item.providerId === provider && (item.id === model || item.config?.deploymentName === model),+ );+ const canonicalModelCard = builtinModels.find(+ (item) => item.id === model || item.config?.deploymentName === model,+ );+ const modelKnowledgeCutoff =+ modelCard?.knowledgeCutoff ??+ (provider === ModelProvider.LobeHub ? canonicalModelCard?.knowledgeCutoff : undefined);+ let modelDisplayName =+ modelCard?.displayName ??+ (provider === ModelProvider.LobeHub ? canonicalModelCard?.displayName : undefined);++ // Custom/remote user models aren't in the bundled model bank, so both cards+ // miss. Fall back to the user's own AI model record so server-side runs still+ // surface identity (the inbox `{{model}}` fallback no longer exists).+ if (!modelDisplayName && ctx.serverDB && ctx.userId) {+ try {+ const aiModelModel = new AiModelModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const userModel = await aiModelModel.findByIdAndProvider(model, provider);+ modelDisplayName = userModel?.displayName ?? undefined;+ } catch (error) {+ log('Failed to resolve user model display name for %s: %O', model, error);+ }+ }++ let modelExtendParams = readExtendParams(modelCard);++ // Aggregation providers (e.g. `lobehub`) may serve a model without copying+ // its origin `settings.extendParams`. Fall back to the canonical model card+ // (matched by id across any provider) so reasoning/thinking params like+ // `thinkingLevel` still reach the model. Mirrors the client-side+ // `transformToAiModelList` re-namespacing behavior.+ if (!modelExtendParams || modelExtendParams.length === 0) {+ modelExtendParams = readExtendParams(canonicalModelCard);+ }++ const modelSupportsPreserveThinkingFromCard =+ Array.isArray(modelExtendParams) && modelExtendParams.includes('preserveThinking');+ // Kimi K2.7+ Code has preserved thinking always active and cannot opt out.+ const kimiForcesPreserveThinking =+ (provider === 'moonshot' || provider === BRANDING_PROVIDER) &&+ isKimiAlwaysPreserveThinkingModel(model);+ // DeepSeek V4 / reasoner thinking models MUST replay the real assistant+ // reasoning in history β this is mandatory, not opt-in. Their+ // Anthropic-compatible API rejects an assistant tool-call turn whose+ // thinking block is missing (HTTP 400), so stripping reasoning leaves the+ // payload builder no choice but to emit a whitespace-only placeholder+ // thinking block. Under large agentic context that degenerate history makes+ // the model emit its final answer *inside* the thinking block with empty+ // visible text (controlled replay: ~30% answer-in-thinking with the+ // placeholder vs ~2.5% when the genuine reasoning is replayed). The only+ // opt-out is a V4 model whose thinking the user explicitly disabled via+ // `deepseekV4ReasoningEffort: 'none'`. That flag is V4-specific and may+ // linger on an agent after switching models, so it must NOT suppress+ // replay for `deepseek-reasoner`, which is thinking-only and always+ // forces reasoning history in the payload builder β suppressing it there+ // would reintroduce the 400/answer-hidden behavior.+ const deepseekV4ThinkingDisabled =+ isDeepSeekV4FamilyModel(model) && agentConfig?.chatConfig?.deepseekV4ReasoningEffort === 'none';+ const deepseekForcesPreserveThinking =+ isDeepSeekThinkingEligibleModel(model) && !deepseekV4ThinkingDisabled;+ const modelForcesPreserveThinking = kimiForcesPreserveThinking || deepseekForcesPreserveThinking;+ const providerSupportsPreserveThinkingFallback =+ provider === 'qwen' || provider === 'zhipu' || provider === 'moonshot';+ const modelSupportsPreserveThinking =+ modelForcesPreserveThinking ||+ modelSupportsPreserveThinkingFromCard ||+ (!modelCard && providerSupportsPreserveThinkingFallback);++ const shouldReplayAssistantReasoning =+ (modelForcesPreserveThinking || preserveThinkingRequested) && modelSupportsPreserveThinking;+ const preserveThinkingForPayload = modelForcesPreserveThinking+ ? true+ : modelSupportsPreserveThinking && typeof preserveThinkingConfigured === 'boolean'+ ? preserveThinkingConfigured+ : undefined;++ const resolvedExtendParams = agentConfig?.chatConfig+ ? applyModelExtendParams({+ chatConfig: agentConfig.chatConfig,+ extendParams: modelExtendParams as ExtendParamsType[] | undefined,+ model,+ })+ : undefined;++ const messagesForContext = shouldReplayAssistantReasoning+ ? (llmPayload.messages as UIChatMessage[])+ : stripAssistantReasoningForReplay(llmPayload.messages as UIChatMessage[]);++ const findModelInfo = (targetModel: string, targetProvider: string) =>+ builtinModels.find((item) => item.id === targetModel && item.providerId === targetProvider) ??+ builtinModels.find((item) => item.id === targetModel);++ return {+ capabilities: {+ isCanUseAudio: (targetModel, targetProvider) =>+ findModelInfo(targetModel, targetProvider)?.abilities?.audio ?? false,+ isCanUseFC: (targetModel, targetProvider) =>+ builtinModels.find((item) => item.id === targetModel && item.providerId === targetProvider)+ ?.abilities?.functionCall ?? true,+ isCanUseVideo: (targetModel, targetProvider) =>+ findModelInfo(targetModel, targetProvider)?.abilities?.video ?? false,+ isCanUseVision: (targetModel, targetProvider) =>+ findModelInfo(targetModel, targetProvider)?.abilities?.vision ?? false,+ },+ messagesForContext,+ modelDisplayName,+ modelKnowledgeCutoff,+ preserveThinkingForPayload,+ resolvedExtendParams,+ shouldReplayAssistantReasoning,+ };+};diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.tsindex bd3bb7052cf..a272f029aae 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts@@ -8,39 +8,15 @@ import {resolveLLMMaxAttempts,resolveLLMRetryBudget,shouldRetryLLM,- stripAssistantReasoningForReplay,UsageCounter,} from '@lobechat/agent-runtime';-import {- type ComposioServiceSummary,- type CredSummary,- excludeDisabledComposioServices,- generateComposioServicesList,- generateCredsList,- resolveAvailableComposioServices,-} from '@lobechat/builtin-tool-creds';-import { builtinTools } from '@lobechat/builtin-tools';import { BRANDING_PROVIDER } from '@lobechat/business-const';-import { COMPOSIO_APP_TYPES } from '@lobechat/const';-import {- type AgentBuilderContext,- type AgentContextDocument,- type AgentGroupConfig,- type OfficialToolItem,- type OnboardingContext,- resolveTopicReferences,- ToolNameResolver,-} from '@lobechat/context-engine';+import { ToolNameResolver } from '@lobechat/context-engine';import {- applyModelExtendParams,type ChatStreamPayload,consumeStreamUntilDone,- isDeepSeekThinkingEligibleModel,- isDeepSeekV4FamilyModel,isEmptyModelCompletion,- isKimiAlwaysPreserveThinkingModel,ModelEmptyError,- type ModelExtendParams,} from '@lobechat/model-runtime';import {context as otelContext,@@ -51,53 +27,24 @@ import {import {buildChatRequestAttributes,buildChatResponseAttributes,- buildContextEngineeringAttributes,chatSpanName,- CONTEXT_ENGINEERING_SPAN_NAME,tracer as agentRuntimeTracer,} from '@lobechat/observability-otel/modules/agent-runtime';-import {- type ChatToolPayload,- getActivePluginIds,- getDisabledPluginIds,- type MessageToolCall,- type UIChatMessage,-} from '@lobechat/types';+import { type ChatToolPayload, type MessageToolCall } from '@lobechat/types';import { sanitizeToolCallArguments, serializePartsForStorage } from '@lobechat/utils';-import { type ExtendParamsType, ModelProvider } from 'model-bank';--import { composioEnv } from '@/config/composio';-import { AgentModel } from '@/database/models/agent';-import { AiModelModel } from '@/database/models/aiModel';-import { FileModel } from '@/database/models/file';-import { MessageModel as MessageModelClass } from '@/database/models/message';-import { PluginModel } from '@/database/models/plugin';-import { TopicModel } from '@/database/models/topic';-import { UserModel } from '@/database/models/user';-import { UserPersonaModel } from '@/database/models/userMemory/persona';+import { fileEnv } from '@/envs/file';-import { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';-import { AgentDocumentsService } from '@/server/services/agentDocuments';import { FileService } from '@/server/services/file';-import { MarketService } from '@/server/services/market';-import { OnboardingService } from '@/server/services/onboarding';-import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';import { nanoid } from '@/utils/uuid';import { type RuntimeExecutorContext } from '../context';-import {- buildPostProcessUrl,- isOperationInterrupted,- log,- resolveRuntimeHistoryCount,- sleep,- timing,-} from '../executorHelpers';+import { isOperationInterrupted, log, sleep, timing } from '../executorHelpers';import { formatErrorEventData } from '../formatErrorEventData';import { classifyLLMError } from '../llmErrorClassification';import { createConversationParentMissingError } from '../messagePersistErrors';import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';+import { buildServerCallLlmContext } from './serverCallLlmContextBuilder';import { resolveServerCallLlmTooling, type ServerCallLlmTooling } from './serverCallLlmTooling';interface PreparedCallLLMContext {@@ -128,7 +75,7 @@ export const callLlm =const provider =prepared?.provider ?? llmPayload.provider ?? state.modelRuntimeConfig?.provider;const tooling = prepared?.tooling ?? resolveServerCallLlmTooling(ctx, state);- const { resolved, resolvedSkills, toolDiscoveryConfig, tools } = tooling;+ const { resolved, tools } = tooling;if (!model || !provider) {throw new Error('Model and provider are required for call_llm instruction');@@ -230,697 +177,19 @@ export const callLlm =try {type ContentPart = { text: string; type: 'text' } | { image: string; type: 'image' };- let shouldReplayAssistantReasoning = false;- let preserveThinkingForPayload: boolean | undefined;- let resolvedExtendParams: ModelExtendParams | undefined;-- // Process messages through serverMessagesEngine to inject system role, knowledge, etc.- // Rebuild params from agentConfig at execution time (capabilities built dynamically)- const agentConfig = ctx.agentConfig;- let processedMessages;- if (agentConfig) {- const { loadModels } = await import('@/business/client/model-bank/loadModels');- const builtinModels = await loadModels();-- const preserveThinkingConfigured =- typeof agentConfig.chatConfig?.preserveThinking === 'boolean'- ? agentConfig.chatConfig.preserveThinking- : undefined;- const preserveThinkingRequested = preserveThinkingConfigured === true;-- const readExtendParams = (- card: (typeof builtinModels)[number] | undefined,- ): string[] | undefined =>- card &&- 'settings' in card &&- card.settings &&- typeof card.settings === 'object' &&- 'extendParams' in card.settings- ? (card.settings as { extendParams?: string[] }).extendParams- : undefined;-- const modelCard = builtinModels.find(- (item) =>- item.providerId === provider &&- (item.id === model || item.config?.deploymentName === model),- );- const canonicalModelCard = builtinModels.find(- (item) => item.id === model || item.config?.deploymentName === model,- );- const modelKnowledgeCutoff =- modelCard?.knowledgeCutoff ??- (provider === ModelProvider.LobeHub ? canonicalModelCard?.knowledgeCutoff : undefined);- let modelDisplayName =- modelCard?.displayName ??- (provider === ModelProvider.LobeHub ? canonicalModelCard?.displayName : undefined);-- // Custom/remote user models aren't in the bundled model bank, so both cards- // miss. Fall back to the user's own AI model record so server-side runs still- // surface identity (the inbox `{{model}}` fallback no longer exists).- if (!modelDisplayName && ctx.serverDB && ctx.userId) {- try {- const aiModelModel = new AiModelModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const userModel = await aiModelModel.findByIdAndProvider(model, provider);- modelDisplayName = userModel?.displayName ?? undefined;- } catch (error) {- log('Failed to resolve user model display name for %s: %O', model, error);- }- }-- let modelExtendParams = readExtendParams(modelCard);-- // Aggregation providers (e.g. `lobehub`) may serve a model without copying- // its origin `settings.extendParams`. Fall back to the canonical model card- // (matched by id across any provider) so reasoning/thinking params like- // `thinkingLevel` still reach the model. Mirrors the client-side- // `transformToAiModelList` re-namespacing behavior.- if (!modelExtendParams || modelExtendParams.length === 0) {- modelExtendParams = readExtendParams(canonicalModelCard);- }-- const modelSupportsPreserveThinkingFromCard =- Array.isArray(modelExtendParams) && modelExtendParams.includes('preserveThinking');- // Kimi K2.7+ Code has preserved thinking always active and cannot opt out.- const kimiForcesPreserveThinking =- (provider === 'moonshot' || provider === BRANDING_PROVIDER) &&- isKimiAlwaysPreserveThinkingModel(model);- // DeepSeek V4 / reasoner thinking models MUST replay the real assistant- // reasoning in history β this is mandatory, not opt-in. Their- // Anthropic-compatible API rejects an assistant tool-call turn whose- // thinking block is missing (HTTP 400), so stripping reasoning leaves the- // payload builder no choice but to emit a whitespace-only placeholder- // thinking block. Under large agentic context that degenerate history makes- // the model emit its final answer *inside* the thinking block with empty- // visible text (controlled replay: ~30% answer-in-thinking with the- // placeholder vs ~2.5% when the genuine reasoning is replayed). The only- // opt-out is a V4 model whose thinking the user explicitly disabled via- // `deepseekV4ReasoningEffort: 'none'`. That flag is V4-specific and may- // linger on an agent after switching models, so it must NOT suppress- // replay for `deepseek-reasoner`, which is thinking-only and always- // forces reasoning history in the payload builder β suppressing it there- // would reintroduce the 400/answer-hidden behavior.- const deepseekV4ThinkingDisabled =- isDeepSeekV4FamilyModel(model) &&- agentConfig.chatConfig?.deepseekV4ReasoningEffort === 'none';- const deepseekForcesPreserveThinking =- isDeepSeekThinkingEligibleModel(model) && !deepseekV4ThinkingDisabled;- const modelForcesPreserveThinking =- kimiForcesPreserveThinking || deepseekForcesPreserveThinking;- const providerSupportsPreserveThinkingFallback =- provider === 'qwen' || provider === 'zhipu' || provider === 'moonshot';- const modelSupportsPreserveThinking =- modelForcesPreserveThinking ||- modelSupportsPreserveThinkingFromCard ||- (!modelCard && providerSupportsPreserveThinkingFallback);-- shouldReplayAssistantReasoning =- (modelForcesPreserveThinking || preserveThinkingRequested) &&- modelSupportsPreserveThinking;- preserveThinkingForPayload = modelForcesPreserveThinking- ? true- : modelSupportsPreserveThinking && typeof preserveThinkingConfigured === 'boolean'- ? preserveThinkingConfigured- : undefined;-- // Resolve model extend params (thinkingLevel, reasoning effort, urlContext, β¦)- // from the agent chat config so the server-side agent runtime forwards the same- // runtime params the client chat service does. Without this, e.g. Gemini 3 Pro's- // `thinkingLevel` never reaches the request and thought summaries come back empty.- if (agentConfig.chatConfig) {- resolvedExtendParams = applyModelExtendParams({- chatConfig: agentConfig.chatConfig,- extendParams: modelExtendParams as ExtendParamsType[] | undefined,- model,- });- }-- const messagesForContext = shouldReplayAssistantReasoning- ? (llmPayload.messages as UIChatMessage[])- : stripAssistantReasoningForReplay(llmPayload.messages as UIChatMessage[]);-- // Extract <refer_topic> tags from messages and fetch summaries.- // Skip if messages already contain injected topic_reference_context- // (e.g., from client-side contextEngineering preprocessing) to avoid double injection.- let topicReferences;- const alreadyHasTopicRefs = (- messagesForContext as Array<{ content: string | unknown }>- ).some(- (m) => typeof m.content === 'string' && m.content.includes('topic_reference_context'),- );-- if (!alreadyHasTopicRefs && ctx.serverDB && ctx.userId) {- const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const messageModel = new MessageModelClass(ctx.serverDB, ctx.userId, ctx.workspaceId);- topicReferences = await resolveTopicReferences(- messagesForContext as Array<{ content: string | unknown }>,- async (topicId) => topicModel.findById(topicId),- async (topicId) => {- const topic = await topicModel.findById(topicId);- return messageModel.query(- {- agentId: topic?.agentId ?? undefined,- groupId: topic?.groupId ?? undefined,- topicId,- },- { postProcessUrl: buildPostProcessUrl(ctx) },- );- },- );- }-- // Fetch agent documents for context injection- let agentDocuments: AgentContextDocument[] | undefined;- const agentId = state.metadata?.agentId;- if (agentId && ctx.serverDB && ctx.userId) {- try {- const agentDocService = new AgentDocumentsService(- ctx.serverDB,- ctx.userId,- state.metadata?.workspaceId ?? ctx.workspaceId,- );- const docs = await agentDocService.getAgentContextDocuments(agentId);- if (docs.length > 0) {- agentDocuments = toAgentContextDocuments(docs);- log('Resolved %d agent documents for agent %s', agentDocuments.length, agentId);- }- } catch (error) {- log('Failed to resolve agent documents for agent %s: %O', agentId, error);- }- }-- // Detect onboarding agent and build context injection- let onboardingContext: OnboardingContext | undefined;- const isOnboardingAgent =- agentConfig?.slug === 'web-onboarding' ||- resolved.enabledToolIds.includes('lobe-web-onboarding');- const alreadyHasOnboardingContext = (- messagesForContext as Array<{ content: string | unknown }>- ).some((message) => {- if (typeof message.content !== 'string') return false;-- return (- message.content.includes('<onboarding_context>') ||- message.content.includes('<current_soul_document>') ||- message.content.includes('<current_user_persona>')- );- });-- if (isOnboardingAgent && !alreadyHasOnboardingContext && ctx.serverDB && ctx.userId) {- try {- const { formatWebOnboardingStateMessage } =- await import('@lobechat/builtin-tool-web-onboarding/utils');- const onboardingService = new OnboardingService(ctx.serverDB, ctx.userId);- const docService = new AgentDocumentsService(- ctx.serverDB,- ctx.userId,- state.metadata?.workspaceId ?? ctx.workspaceId,- );- const personaModel = new UserPersonaModel(ctx.serverDB, ctx.userId);-- const [onboardingState, soulDoc, persona, userInfo] = await Promise.all([- onboardingService.getState(),- onboardingService- .getInboxAgentId()- .then((inboxAgentId) =>- inboxAgentId ? docService.getDocumentByFilename(inboxAgentId, 'SOUL.md') : null,- )- .catch((error) => {- log('Failed to fetch SOUL.md for onboarding context: %O', error);- return null;- }),- personaModel.getLatestPersonaDocument().catch((error) => {- log('Failed to fetch user persona for onboarding context: %O', error);- return null;- }),- onboardingService.getInitialUserInfo().catch((error) => {- log('Failed to fetch initial user info for onboarding context: %O', error);- return undefined;- }),- ]);-- onboardingContext = {- discoveryUserMessageCount: onboardingState.discoveryUserMessageCount,- personaContent: persona?.persona ?? null,- phaseGuidance: formatWebOnboardingStateMessage(onboardingState),- remainingDiscoveryExchanges: onboardingState.remainingDiscoveryExchanges,- soulContent: soulDoc?.content ?? null,- userInfo,- };- log('Built onboarding context for agent %s, phase: %s', agentId, onboardingState.phase);- } catch (error) {- log('Failed to build onboarding context: %O', error);- }- }-- // Build additional placeholder variables for the lobehub builtin skill- // (`packages/builtin-skills/src/lobehub/content.ts`) so it can render- // `{{agent_id}}` / `{{agent_title}}` / `{{topic_id}}` etc. into the- // model's prompt without needing a separate context injector.- //- // - agent_title / agent_description: read directly from agentConfig,- // which is the result of AgentModel.getAgentConfig() and already- // contains the full enriched agent record (title, description, ...).- // No extra query needed.- // - topic_title: requires a single primary-key lookup against the- // topics table. Skipped when topicId is missing or the lookup fails- // (best-effort, falls back to empty string so the template still- // renders cleanly).- const lobehubSkillAgentId = state.metadata?.agentId;- const lobehubSkillTopicId = state.metadata?.topicId;- const lobehubSkillAgentMeta = state.metadata?.agentConfig as- { description?: string | null; title?: string | null } | undefined;-- let lobehubSkillTopicTitle = '';- if (lobehubSkillTopicId && ctx.serverDB && ctx.userId) {- try {- const topicModelForLobehub = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const topicRecord = await topicModelForLobehub.findById(lobehubSkillTopicId);- lobehubSkillTopicTitle = topicRecord?.title ?? '';- } catch (error) {- log('Failed to load topic title for lobehub skill placeholders: %O', error);- }- }-- const lobehubSkillVariables: Record<string, string> = {- agent_id: lobehubSkillAgentId ?? '',- agent_title: lobehubSkillAgentMeta?.title ?? '',- agent_description: lobehubSkillAgentMeta?.description ?? '',- topic_id: lobehubSkillTopicId ?? '',- topic_title: lobehubSkillTopicTitle,- };-- // ββ Tool-specific template variable resolution ββββββββββββββββββββ- // The client-side contextEngineering.ts resolves these via Zustand stores- // and lambdaClient. In execAgent (server/bot) mode we must fetch from DB- // directly. Each block is gated on the relevant tool being enabled.-- // {{username}} / {{language}} β used by memory and creds system roles.- // Single indexed DB lookup; cheap enough to run on each call_llm step.- let serverUsername = '';- let serverLanguage = '';- if (ctx.serverDB && ctx.userId) {- try {- const userInfo = await UserModel.getInfoForAIGeneration(ctx.serverDB, ctx.userId);- serverUsername = userInfo.userName;- serverLanguage = userInfo.responseLanguage;- } catch (error) {- log('Failed to fetch user info for {{username}}/{{language}} substitution: %O', error);- }- }-- // {{sandbox_enabled}} β mirrors client-side check for lobe-cloud-sandbox.- const sandboxEnabled = String(resolved.enabledToolIds.includes('lobe-cloud-sandbox'));-- // {{sandbox_uploaded_files}} β lists the topic/session files that are- // synced into the sandbox upload dir, so the agent knows they exist.- // Mirrors the bootstrap query in SandboxMiddlewareService.- let sandboxUploadedFiles = '';- if (sandboxEnabled === 'true' && ctx.serverDB && ctx.userId && lobehubSkillTopicId) {- try {- const { formatUploadedFilesPrompt } =- await import('@lobechat/builtin-tool-cloud-sandbox');- const fileModel = new FileModel(ctx.serverDB, ctx.userId);- const uploadedFiles = await fileModel.findFilesToInitInSandbox(lobehubSkillTopicId);- sandboxUploadedFiles = formatUploadedFilesPrompt(uploadedFiles);- } catch (error) {- log('Failed to resolve files for {{sandbox_uploaded_files}} substitution: %O', error);- }- }-- // {{session_date}} β current date formatted for user's timezone.- const sessionDate = new Intl.DateTimeFormat('en-US', {- day: 'numeric',- month: 'long',- timeZone: ctx.userTimezone || 'UTC',- weekday: 'long',- year: 'numeric',- }).format(new Date());-- // {{memory_effort}} β read from agentConfig chatConfig; no extra query needed.- const memoryEffort = String(- (state.metadata?.agentConfig as any)?.chatConfig?.memory?.effort ?? '',- );-- // {{CREDS_LIST}} β used by lobe-creds system role.- // Always fetched when userId is available so substitution works regardless of which- // execution path (execAgent / client-side activator) injected the system role.- let credsListStr = '';- if (ctx.userId) {- try {- const marketService = new MarketService({ userInfo: { userId: ctx.userId } });- // Inside a workspace, the agent must only see the workspace's shared- // organization credentials β personal creds are not visible here (LOBE-10978).- const credsResult = ctx.workspaceId- ? await marketService.market.organizations- .creds({ workspaceId: ctx.workspaceId })- .list()- : await marketService.market.creds.list();- const userCreds = (credsResult as any)?.data ?? [];- credsListStr = generateCredsList(- userCreds.map((cred: any): CredSummary => ({- description: cred.description,- key: cred.key,- name: cred.name,- // Only present on the workspace-merged list (organizations.creds().list())- // above β tells the AI whether this credential is the workspace's own or a- // member's shared one, so it never misrepresents whose secret it's using.- ownerDisplayName: cred.ownerDisplayName,- ownerType: cred.ownerType,- type: cred.type,- })),- );- log('Fetched %d creds for {{CREDS_LIST}} substitution', userCreds.length);- } catch (error) {- log('Failed to fetch creds for {{CREDS_LIST}} substitution: %O', error);- }- }-- // {{COMPOSIO_SERVICES_LIST}} β used by lobe-creds system role (Composio integrations section).- let composioServicesListStr = '';- if (ctx.serverDB && ctx.userId && !!composioEnv.COMPOSIO_API_KEY) {- try {- const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const allPlugins = await pluginModel.query();- const validComposioIds = new Set(COMPOSIO_APP_TYPES.map((t) => t.identifier));- const connectedIds = new Set(- allPlugins- .filter(- (p) =>- validComposioIds.has(p.identifier) &&- (p.customParams as any)?.composio?.status === 'ACTIVE',- )- .map((p) => p.identifier),- );- // Disabled services are dropped from both lists β not surfaced as- // "connected, use directly" (this agent shouldn't use it) nor as- // "available to connect" (the account-level OAuth connection, if- // any, is untouched; this agent just isn't meant to see it).- let disabledIdSet = new Set<string>();- if (agentId) {- const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const agentConfig = await agentModel.getAgentConfigById(agentId);- disabledIdSet = new Set(getDisabledPluginIds(agentConfig?.plugins ?? undefined));- }- const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(- COMPOSIO_APP_TYPES.filter((t) => connectedIds.has(t.identifier)),- disabledIdSet,- ).map((t) => ({ identifier: t.identifier, name: t.label }));- const available = resolveAvailableComposioServices(- COMPOSIO_APP_TYPES,- connectedIds,- disabledIdSet,- );- composioServicesListStr = generateComposioServicesList(connected, available);- log(- 'Fetched Composio services for {{COMPOSIO_SERVICES_LIST}}: connected=%d, available=%d',- connected.length,- available.length,- );- } catch (error) {- log(- 'Failed to fetch Composio services for {{COMPOSIO_SERVICES_LIST}} substitution: %O',- error,- );- }- }-- // Agent Builder (gateway / server mode): the `<current_agent_context>`- // that tells the builder LLM WHICH agent it is editing is built- // CLIENT-side in chat mode (services/chat/index.ts). In gateway mode that- // client code never runs, so without this the context is never injected- // and the builder answers with its OWN config instead of the edited- // agent's. `state.metadata.editingAgentId` is the agent being configured- // (the builder builtin is `state.metadata.agentId`).- let agentBuilderContext: AgentBuilderContext | undefined;- const editingAgentId = state.metadata?.editingAgentId;- if (editingAgentId && ctx.serverDB && ctx.userId) {- try {- const editingAgentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const editingConfig = (await editingAgentModel.getAgentConfigById(- editingAgentId,- )) as Record<string, any> | null;- if (editingConfig) {- // Build the `<available_official_tools>` list the same way the- // client does (services/chat/index.ts). Without it the builder- // prompt β which now relies on injected official tools instead of a- // search API β can't see installable builtin/Composio tools or their- // enabled/connected status, so the model may pick invalid ids or- // claim a supported tool is unavailable.- const enabledPlugins: string[] = getActivePluginIds(- Array.isArray(editingConfig.plugins) ? editingConfig.plugins : undefined,- );- const composioIdentifiers = new Set(COMPOSIO_APP_TYPES.map((t) => t.identifier));- const officialTools: OfficialToolItem[] = [];-- // Builtin tools β exclude hidden/infra tools (mirrors the client's- // `metaList`) and Composio entries (listed separately below).- for (const tool of builtinTools) {- if (tool.hidden) continue;- if (composioIdentifiers.has(tool.identifier)) continue;- officialTools.push({- description: tool.manifest?.meta?.description,- enabled: enabledPlugins.includes(tool.identifier),- identifier: tool.identifier,- installed: true,- name: tool.manifest?.meta?.title || tool.identifier,- type: 'builtin',- });- }-- // Composio MCP servers β only when Composio is configured for this- // deployment. Connection status mirrors the existing- // {{COMPOSIO_SERVICES_LIST}} logic (ACTIVE composio plugin rows).- if (composioEnv.COMPOSIO_API_KEY) {- try {- const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const allPlugins = await pluginModel.query();- const connectedComposioIds = new Set(- allPlugins- .filter(- (p) =>- composioIdentifiers.has(p.identifier) &&- (p.customParams as any)?.composio?.status === 'ACTIVE',- )- .map((p) => p.identifier),- );- for (const t of COMPOSIO_APP_TYPES) {- officialTools.push({- description: `LobeHub Mcp Server: ${t.label}`,- enabled: enabledPlugins.includes(t.identifier),- identifier: t.identifier,- installed: connectedComposioIds.has(t.identifier),- name: t.label,- type: 'composio',- });- }- } catch (composioError) {- log('Failed to load Composio status for agentBuilderContext: %O', composioError);- }- }-- agentBuilderContext = {- config: {- chatConfig: editingConfig.chatConfig ?? undefined,- model: editingConfig.model ?? undefined,- openingMessage: editingConfig.openingMessage ?? undefined,- openingQuestions: editingConfig.openingQuestions ?? undefined,- params: editingConfig.params ?? undefined,- plugins: enabledPlugins,- provider: editingConfig.provider ?? undefined,- systemRole: editingConfig.systemRole ?? undefined,- },- meta: {- avatar: editingConfig.avatar ?? undefined,- backgroundColor: editingConfig.backgroundColor ?? undefined,- description: editingConfig.description ?? undefined,- tags: editingConfig.tags ?? undefined,- title: editingConfig.title ?? undefined,- },- ...(officialTools.length > 0 && { officialTools }),- };- }- } catch (error) {- log(- 'Failed to build agentBuilderContext for editing agent %s: %O',- editingAgentId,- error,- );- }- }-- const contextEngineInput = {- agentDocuments,- ...(agentBuilderContext && { agentBuilderContext }),- // The group/bot member roster is resolved once at op creation- // (AiAgentService.execAgent β buildGroupAgentContext) and snapshotted- // into op metadata, mirroring agentConfig/botContext β no per-step DB- // lookup here.- agentGroup: state.metadata?.agentGroup as AgentGroupConfig | undefined,- // Bridge the @-mentioned agents (persisted into the runtime- // initialContext by AiAgentService.execAgent) into the agent-management- // context so AgentManagementContextInjector injects the delegation- // block, prompting the supervisor to `callAgent` the mentioned agents.- // Mirrors the client's contextEngineering bridge; scoped to mention- // runs only (undefined otherwise) so ordinary runs are unaffected.- agentManagementContext: (state as any).initialContext?.initialContext?.mentionedAgents- ?.length- ? {- mentionedAgents: (state as any).initialContext.initialContext.mentionedAgents,- }- : undefined,- additionalVariables: {- ...state.metadata?.deviceSystemInfo,- ...lobehubSkillVariables,- // User identity variables- username: serverUsername,- language: serverLanguage,- session_date: sessionDate,- // Creds tool variables- sandbox_enabled: sandboxEnabled,- sandbox_uploaded_files: sandboxUploadedFiles,- CREDS_LIST: credsListStr,- COMPOSIO_SERVICES_LIST: composioServicesListStr,- // Memory tool variables- memory_effort: memoryEffort,- },- userTimezone: ctx.userTimezone,- capabilities: {- isCanUseAudio: (m: string, p: string) => {- const info =- builtinModels.find((item) => item.id === m && item.providerId === p) ??- builtinModels.find((item) => item.id === m);- return info?.abilities?.audio ?? false;- },- isCanUseFC: (m: string, p: string) => {- const info = builtinModels.find((item) => item.id === m && item.providerId === p);- return info?.abilities?.functionCall ?? true;- },- isCanUseVideo: (m: string, p: string) => {- const info =- builtinModels.find((item) => item.id === m && item.providerId === p) ??- builtinModels.find((item) => item.id === m);- return info?.abilities?.video ?? false;- },- isCanUseVision: (m: string, p: string) => {- // Aggregator providers (e.g. lobehub) route to upstream model cards- // that live under the original provider's id in the registry, so- // fall back to a cross-provider lookup by model id when the- // (model, provider) pair has no direct entry.- const info =- builtinModels.find((item) => item.id === m && item.providerId === p) ??- builtinModels.find((item) => item.id === m);- return info?.abilities?.vision ?? false;- },- },- botPlatformContext: ctx.botPlatformContext,- discordContext: ctx.discordContext,- enableHistoryCount: agentConfig.chatConfig?.enableHistoryCount ?? undefined,- evalContext: ctx.evalContext,- forceFinish: state.forceFinish,- historyCount: resolveRuntimeHistoryCount(agentConfig.chatConfig?.historyCount),- initialContext: (state as any).initialContext?.initialContext,- knowledge: {- fileContents: agentConfig.files- ?.filter((f: { enabled?: boolean | null }) => f.enabled === true)- .map((f: { content?: string | null; id?: string; name?: string }) => ({- content: f.content ?? '',- fileId: f.id ?? '',- filename: f.name ?? '',- })),- knowledgeBases: agentConfig.knowledgeBases- ?.filter((kb: { enabled?: boolean | null }) => kb.enabled === true)- .map((kb: { id?: string; name?: string }) => ({- id: kb.id ?? '',- name: kb.name ?? '',- })),- },- messages: messagesForContext,- model,- modelDisplayName,- modelKnowledgeCutoff,- provider,- systemRole: agentConfig.systemRole ?? undefined,- toolDiscoveryConfig,- toolsConfig: {- manifests: Object.values(resolved.manifestMap),- tools: resolved.enabledToolIds,- },- userMemory: state.metadata?.userMemory,-- // Skills configuration for <available_skills> injection.- // In chat mode the MessagesEngine force-disables this injector via- // its `enableAgentMode` param β no extra gate needed here.- ...(resolvedSkills?.enabledSkills?.length && {- skillsConfig: { enabledSkills: resolvedSkills.enabledSkills },- }),- enableAgentMode: agentConfig.chatConfig?.enableAgentMode,-- // Topic reference summaries- ...(topicReferences && { topicReferences }),- ...(onboardingContext && { onboardingContext }),- };-- processedMessages = await agentRuntimeTracer.startActiveSpan(- CONTEXT_ENGINEERING_SPAN_NAME,- {- attributes: buildContextEngineeringAttributes({- hasImages: (messagesForContext as Array<{ content?: unknown }>).some(- (m) =>- Array.isArray(m.content) &&- (m.content as Array<{ type?: string }>).some((p) => p?.type === 'image_url'),- ),- historyCompressed:- Array.isArray(messagesForContext) &&- messagesForContext.some((m: { role?: string }) => m?.role === 'compressedGroup'),- knowledgeCount:- (contextEngineInput.knowledge?.knowledgeBases?.length ?? 0) +- (contextEngineInput.knowledge?.fileContents?.length ?? 0),- knowledgeInjected:- (contextEngineInput.knowledge?.knowledgeBases?.length ?? 0) > 0 ||- (contextEngineInput.knowledge?.fileContents?.length ?? 0) > 0,- memoryInjected: Boolean(contextEngineInput.userMemory?.memories),- messageCount: messagesForContext.length,- operationId,- stepIndex,- systemRoleLength: contextEngineInput.systemRole?.length,- toolCount: contextEngineInput.toolsConfig?.tools?.length ?? 0,- }),- },- async (ceSpan) => {- try {- const result = await serverMessagesEngine(contextEngineInput);- ceSpan.setAttribute('lobehub.context.message_count', result.length);- return result;- } catch (error) {- ceSpan.recordException(error as Error);- ceSpan.setStatus({- code: SpanStatusCode.ERROR,- message: error instanceof Error ? error.message : String(error),- });- throw error;- } finally {- ceSpan.end();- }- },- );-- // Hand context engine input/output to the trace sink out-of-band.- // Omit large/redundant fields to reduce snapshot size:- // - input.messages: reconstructible from step's messagesBaseline + messagesDelta- // - input.toolsConfig: static per operation, ~47KB of manifests repeated every call_llm step- // Keep output (processedMessages) β needed by inspect CLI for --env, --system-role, -m- const {- messages: _inputMsgs,- toolsConfig: _toolsConfig,- ...contextEngineInputLite- } = contextEngineInput;- ctx.tracingContextEngine?.(- { ...contextEngineInputLite, toolCount: _toolsConfig?.tools?.length ?? 0 },- processedMessages,- );- } else {- processedMessages = llmPayload.messages;- }+ const {+ preserveThinkingForPayload,+ processedMessages,+ resolvedExtendParams,+ shouldReplayAssistantReasoning,+ } = await buildServerCallLlmContext({+ ctx,+ llmPayload,+ model,+ provider,+ state,+ tooling,+ });// A turn must carry at least one non-system message. Anthropic-compatible// providers (anthropic / deepseek) move `role: system` into a separatediff --git a/packages/model-runtime/src/core/usageConverters/openai.test.ts b/packages/model-runtime/src/core/usageConverters/openai.test.tsindex cb8e946a960..3d621d913c3 100644--- a/packages/model-runtime/src/core/usageConverters/openai.test.ts+++ b/packages/model-runtime/src/core/usageConverters/openai.test.ts@@ -375,6 +375,7 @@ describe('convertUsage', () => {const responseUsage = {input_tokens: 100,input_tokens_details: {+ cache_write_tokens: 0,cached_tokens: 0,},output_tokens: 200,@@ -413,9 +414,13 @@ describe('convertUsage', () => {const responseUsage = {input_tokens: 4198,input_tokens_details: {+ cache_write_tokens: 0,cached_tokens: 4198,},output_tokens: 598,+ output_tokens_details: {+ reasoning_tokens: 0,+ },total_tokens: 4796,} as OpenAI.Responses.ResponseUsage;@@ -462,7 +467,14 @@ describe('convertUsage', () => {const responseUsage = {input_tokens: 1_000_000,+ input_tokens_details: {+ cache_write_tokens: 0,+ cached_tokens: 0,+ },output_tokens: 1_000_000,+ output_tokens_details: {+ reasoning_tokens: 0,+ },total_tokens: 2_000_000,} as OpenAI.Responses.ResponseUsage;