π€― 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(mecha): decide the model parameters of an LLM call in the shared core (#19586)
Arvin Xu119c09ab395a
diff --git a/.agents/skills/add-model-provider/references/integration-map.md b/.agents/skills/add-model-provider/references/integration-map.mdindex 246816edf09..4b8a69e3f9c 100644--- a/.agents/skills/add-model-provider/references/integration-map.md+++ b/.agents/skills/add-model-provider/references/integration-map.md@@ -4,23 +4,23 @@ Use this map to locate the current code. Verify paths and consumers before editi## Registration and Configuration-| Concern | Current location | What to verify |-| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |-| Provider identity | `packages/model-bank/src/const/modelProvider.ts` | Stable `ModelProvider` ID used by all maps |-| Provider card | `packages/model-bank/src/modelProviders/<provider>.ts` | Name, public URLs, `checkModel`, authentication, fetcher and browser settings |-| Provider registration | `packages/model-bank/src/modelProviders/index.ts` | Import, `DEFAULT_MODEL_PROVIDER_LIST` position, card export |-| Model cards | `packages/model-bank/src/aiModels/<provider>.ts` | Evidence-backed metadata, supported abilities, default enablement, prices |-| Model registration | `packages/model-bank/src/aiModels/index.ts` | Import, `staticModelMap`, named export keyed to the provider ID |-| Package access | `packages/model-bank/package.json` | New model module's subpath export, including filename casing |-| Runtime implementation | `packages/model-runtime/src/providers/<provider>/index.ts` | Factory reuse, endpoint, protocol, payload and response behavior |-| Runtime registration | `packages/model-runtime/src/runtimeMap.ts`, `packages/model-runtime/src/index.ts` | ID-to-runtime map and public export |-| Distinct routed adapter | `packages/model-runtime/src/core/RouterRuntime/apiTypes.ts`, `baseRuntimeMap.ts` | Add only when this adapter is needed; test runtime selection |-| API-key environment | `packages/env/src/llm.ts` | Schema and `runtimeEnv`; enablement semantics |-| Server provider configuration | `apps/server/src/globalConfig/genServerAiProviderConfig.ts` | Generic uppercase ID conventions, model list and enablement overrides |-| Runtime credentials/options | `apps/server/src/modules/ModelRuntime/index.ts` | Generic API-key/proxy handling versus provider-specific initialization |-| OAuth flow | `apps/server/src/services/oauthDeviceFlow/`, `apps/server/src/routers/lambda/oauthDeviceFlow.ts` | Factory registration, token exchange/refresh, account metadata, disconnect |-| New parameter controls | `packages/model-bank/src/types/aiModel.ts`, `packages/types/src/agent/chatConfig.ts`, `src/services/chat/mecha/modelParamsResolver.ts` | Trace consumers into controls and translations; avoid changing types alone |-| Default list consumption | `packages/database/src/repositories/aiInfra/index.ts`, `src/store/aiInfra/slices/aiProvider/selectors.ts` | Built-in order versus enabled-provider custom sort |+| Concern | Current location | What to verify |+| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Provider identity | `packages/model-bank/src/const/modelProvider.ts` | Stable `ModelProvider` ID used by all maps |+| Provider card | `packages/model-bank/src/modelProviders/<provider>.ts` | Name, public URLs, `checkModel`, authentication, fetcher and browser settings |+| Provider registration | `packages/model-bank/src/modelProviders/index.ts` | Import, `DEFAULT_MODEL_PROVIDER_LIST` position, card export |+| Model cards | `packages/model-bank/src/aiModels/<provider>.ts` | Evidence-backed metadata, supported abilities, default enablement, prices |+| Model registration | `packages/model-bank/src/aiModels/index.ts` | Import, `staticModelMap`, named export keyed to the provider ID |+| Package access | `packages/model-bank/package.json` | New model module's subpath export, including filename casing |+| Runtime implementation | `packages/model-runtime/src/providers/<provider>/index.ts` | Factory reuse, endpoint, protocol, payload and response behavior |+| Runtime registration | `packages/model-runtime/src/runtimeMap.ts`, `packages/model-runtime/src/index.ts` | ID-to-runtime map and public export |+| Distinct routed adapter | `packages/model-runtime/src/core/RouterRuntime/apiTypes.ts`, `baseRuntimeMap.ts` | Add only when this adapter is needed; test runtime selection |+| API-key environment | `packages/env/src/llm.ts` | Schema and `runtimeEnv`; enablement semantics |+| Server provider configuration | `apps/server/src/globalConfig/genServerAiProviderConfig.ts` | Generic uppercase ID conventions, model list and enablement overrides |+| Runtime credentials/options | `apps/server/src/modules/ModelRuntime/index.ts` | Generic API-key/proxy handling versus provider-specific initialization |+| OAuth flow | `apps/server/src/services/oauthDeviceFlow/`, `apps/server/src/routers/lambda/oauthDeviceFlow.ts` | Factory registration, token exchange/refresh, account metadata, disconnect |+| New parameter controls | `packages/model-bank/src/types/aiModel.ts`, `packages/types/src/agent/chatConfig.ts`, `packages/mecha/src/modelParams/resolveModelParams.ts` | The shared resolver owns the policy for every host; `src/services/chat/mecha/modelParamsResolver.ts` and `apps/server/src/modules/Mecha/ModelParams/providers.ts` only fetch. Trace consumers into controls and translations; avoid changing types alone |+| Default list consumption | `packages/database/src/repositories/aiInfra/index.ts`, `src/store/aiInfra/slices/aiProvider/selectors.ts` | Built-in order versus enabled-provider custom sort |Provider-specific `*_MODEL_LIST` and `*_PROXY_URL` may be consumed dynamically. Trace the configuration path before adding redundant schema entries or documenting an unsupported variable. The deprecated `LOBE_DEFAULT_MODEL_LIST` is not a substitute for the modern model map; inspect actual consumers before changing it.diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.tsindex 617a45ef2e1..ec235a84406 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.ts@@ -28,7 +28,10 @@ export class ServerContextBuilder implements ContextBuilder {return {messages: result.processedMessages,- modelParameters: result.resolvedExtendParams,+ modelParameters: {+ ...result.resolvedExtendParams,+ ...(typeof result.stream === 'boolean' && { stream: result.stream }),+ },preserveThinking: result.preserveThinkingForPayload,replayAssistantReasoning: result.shouldReplayAssistantReasoning,resolvedTools: tooling.resolved,diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.tsindex bf2a9d8804a..72efc1c15f7 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts@@ -1,5 +1,6 @@// @vitest-environment nodeimport { ModelRuntime } from '@lobechat/model-runtime';+import { tracer as agentRuntimeTracer } from '@lobechat/observability-otel/modules/agent-runtime';import { describe, expect, it, vi } from 'vitest';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';@@ -33,3 +34,42 @@ describe('ServerLLMTransport.stream Β· conversation affinity', () => {]);});});++describe('ServerLLMTransport.createTrace Β· streaming mode', () => {+ it('records the streaming mode the built context resolved, not the operation default', () => {+ const startSpan = vi.spyOn(agentRuntimeTracer, 'startSpan');+ const ctx = { operationId: 'op-1', stepIndex: 0, userId: 'user-1' } as RuntimeExecutorContext;++ new ServerLLMTransport(ctx).createTrace({+ assistantMessageId: 'msg-1',+ context: {+ messages: [],+ modelParameters: { stream: false },+ replayAssistantReasoning: false,+ },+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(startSpan).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({+ attributes: expect.objectContaining({ 'gen_ai.request.stream': false }),+ }),+ );++ // An explicit operation-level stream is already folded into the context;+ // without any context the operation value still applies.+ new ServerLLMTransport({ ...ctx, stream: false }).createTrace({+ assistantMessageId: 'msg-2',+ model: 'gpt-4',+ provider: 'openai',+ });+ expect(startSpan).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({+ attributes: expect.objectContaining({ 'gen_ai.request.stream': false }),+ }),+ );+ });+});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex e1238568b01..b2e2addc393 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -1,5 +1,6 @@import type {BlobStore,+ ContextBuildOutput,LLMAttemptExecution,LLMAttemptInput,LLMAttemptOutput,@@ -141,6 +142,19 @@ class ServerLLMRetryPolicy implements LLMRetryPolicy {}}+/**+ * The streaming mode the request really uses: the built context carries the+ * agent's chat-config decision (with an explicit operation-level `stream`+ * already folded in), so the payload and the trace must read the same value.+ */+const resolveRequestStream = (+ ctx: RuntimeExecutorContext,+ context: ContextBuildOutput | undefined,+): boolean => {+ const fromContext = (context?.modelParameters as { stream?: boolean } | undefined)?.stream;+ return fromContext ?? ctx.stream ?? true;+};+class ServerLLMTrace implements LLMTrace {private readonly chatContext: ReturnType<typeof otelTrace.setSpan>;private readonly chatSpan: ReturnType<typeof agentRuntimeTracer.startSpan>;@@ -166,7 +180,7 @@ class ServerLLMTrace implements LLMTrace {provider: input.provider,requestModel: input.model,stepIndex: ctx.stepIndex,- stream: ctx.stream ?? true,+ stream: resolveRequestStream(ctx, input.context),}),kind: SpanKind.CLIENT,});@@ -307,7 +321,7 @@ export class ServerLLMTransport implements LLMTransport {const chatPayload = {messages: input.context.messages as ChatStreamPayload['messages'],model: input.model,- stream: this.ctx.stream ?? true,+ stream: resolveRequestStream(this.ctx, input.context),tools,...(input.context.modelParameters as Partial<ChatStreamPayload>),...(typeof input.context.preserveThinking === 'boolean' && {diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex ba0b6687145..23b1785b9e6 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -15,7 +15,6 @@ import {} from '@/server/modules/Mecha/ContextEngineering/providers';import type { RuntimeExecutorContext } from '../context';-import { resolveRuntimeHistoryCount } from '../executorHelpers';import {resolveServerCallLlmContextHints,type ServerCallLlmContextHints,@@ -36,6 +35,8 @@ export interface ServerCallLlmContextBuildResult {processedMessages: ChatStreamPayload['messages'];resolvedExtendParams?: ServerCallLlmContextHints['resolvedExtendParams'];shouldReplayAssistantReasoning: boolean;+ /** An explicit operation-level `stream` wins; otherwise the agent's chat config. */+ stream?: boolean;}export const buildServerCallLlmContext = async ({@@ -66,6 +67,8 @@ export const buildServerCallLlmContext = async ({});const {capabilities,+ enableAgentMode,+ historyCount,messagesForContext,modelDisplayName,modelKnowledgeCutoff,@@ -132,7 +135,7 @@ export const buildServerCallLlmContext = async ({...(facts.step.groupAgentBuilderContext && {groupAgentBuilderContext: facts.step.groupAgentBuilderContext,}),- historyCount: resolveRuntimeHistoryCount(agentConfig.chatConfig?.historyCount),+ historyCount,initialContext: (state as any).initialContext?.initialContext,knowledge: {fileContents: agentConfig.files@@ -167,7 +170,7 @@ export const buildServerCallLlmContext = async ({...(resolvedSkills?.enabledSkills?.length && {skillsConfig: { enabledSkills: resolvedSkills.enabledSkills },}),- enableAgentMode: agentConfig.chatConfig?.enableAgentMode,+ enableAgentMode,...(facts.step.topicReferences && { topicReferences: facts.step.topicReferences }),...(facts.step.onboardingContext && { onboardingContext: facts.step.onboardingContext }),};@@ -235,5 +238,6 @@ export const buildServerCallLlmContext = async ({processedMessages,resolvedExtendParams,shouldReplayAssistantReasoning,+ stream: ctx.stream ?? contextHints.stream,};};diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.tsindex a48814ccdc6..62b51d87c1f 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts@@ -3,30 +3,20 @@ import {type CallLLMPayload,stripAssistantReasoningForReplay,} from '@lobechat/agent-runtime';-import { BRANDING_PROVIDER } from '@lobechat/business-const';import {- applyModelExtendParams,- isDeepSeekThinkingEligibleModel,- isDeepSeekV4FamilyModel,- isKimiAlwaysPreserveThinkingModel,- type ModelExtendParams,- resolveEffectiveReasoningChatConfig,-} from '@lobechat/model-runtime';-import type { LobeAgentChatConfig, UIChatMessage } from '@lobechat/types';-import {- type AiModelReasoningConfig,- type ExtendParamsType,- type LobeDefaultAiModelListItem,- MODEL_REASONING_EXTEND_PARAMS,- ModelProvider,-} from 'model-bank';--import { AiModelModel } from '@/database/models/aiModel';-import { TopicModel } from '@/database/models/topic';+ type ResolvedModelExtendParamList,+ type ResolvedModelParams,+ resolveModelExtendParamList,+ resolveModelParams,+} from '@lobechat/mecha';+import type { UIChatMessage } from '@lobechat/types';+import type { LobeDefaultAiModelListItem } from 'model-bank';++import { loadModels } from '@/business/client/model-bank/loadModels';+import type { AiModelModel } from '@/database/models/aiModel';+import { createServerModelParamsProviders } from '@/server/modules/Mecha/ModelParams/providers';import type { RuntimeExecutorContext } from '../context';-import { log } from '../executorHelpers';-import { resolveModelMediaCapabilities } from '../resolveModelMediaCapabilities';interface ResolveServerCallLlmContextHintsInput {ctx: RuntimeExecutorContext;@@ -36,38 +26,28 @@ interface ResolveServerCallLlmContextHintsInput {world?: AgentWorldSnapshot;}-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;- };+export interface ServerCallLlmContextHints extends Pick<+ ResolvedModelParams,+ | 'capabilities'+ | 'enableAgentMode'+ | 'historyCount'+ | 'modelDisplayName'+ | 'modelKnowledgeCutoff'+ | 'preserveThinkingForPayload'+ | 'resolvedExtendParams'+ | 'shouldReplayAssistantReasoning'+ | 'stream'+> {messagesForContext: UIChatMessage[];- modelDisplayName?: string;- modelKnowledgeCutoff?: string;- preserveThinkingForPayload?: boolean;- resolvedExtendParams?: ModelExtendParams & { enabledSearch?: boolean };- shouldReplayAssistantReasoning: boolean;}-export interface ResolvedModelExtendParams {- /** Bundled card matched by id across any provider (aggregation fallback). */- canonicalModelCard?: LobeDefaultAiModelListItem;- /** Bundled card for exactly `provider`/`model`. */- modelCard?: LobeDefaultAiModelListItem;- /** Effective extend params: user row β provider card β canonical card. */- modelExtendParams?: string[];- /** True when any effort-family / reasoningMode param is among `modelExtendParams`. */- modelHasReasoningExtendParams: boolean;- userModelRow?: Awaited<ReturnType<AiModelModel['findByIdAndProvider']>>;-}+export type ResolvedModelExtendParams = ResolvedModelExtendParamList;/**- * Resolve which extend params a model can consume for this user, matching the- * client's `getEnabledModels` merge. Shared by the per-attempt LLM hints and- * the topic-creation reasoning snapshot (`turnSetup`), so both agree on- * whether a model is governed by the reasoning extend-params family.+ * Which extend params a model can consume for this user. Shared by the+ * per-attempt LLM hints and the topic-creation reasoning snapshot+ * (`turnSetup`), so both agree on whether a model is governed by the+ * reasoning extend-params family.*/export const resolveModelExtendParamsForUser = async ({aiModelModel,@@ -81,73 +61,32 @@ export const resolveModelExtendParamsForUser = async ({model: string;provider: string;}): Promise<ResolvedModelExtendParams> => {- const builtinModels =- preloadedModels ??- (await (await import('@/business/client/model-bank/loadModels')).loadModels());-- const readExtendParams = (card: LobeDefaultAiModelListItem | 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,- );-- // The user's own AI model row serves two purposes: custom/remote models miss- // both bundled cards entirely (displayName + extendParams live only on the- // row), and builtin models may carry user-edited `settings.extendParams`- // from a provider-settings edit, which the client honors by merging user- // settings over the card. One indexed read per attempt.- let userModelRow: Awaited<ReturnType<AiModelModel['findByIdAndProvider']>> | undefined;- if (aiModelModel) {- try {- userModelRow = await aiModelModel.findByIdAndProvider(model, provider);- } catch (error) {- log('Failed to resolve user model row for %s: %O', model, error);- }- }-- // User-edited settings win over the bundled card, matching the client's- // `getEnabledModels` settings merge (arrays replace wholesale there, so an- // explicit empty array is an opt-out from the card's params, not a miss β- // only a row without `extendParams` falls back to the cards).- let modelExtendParams: string[] | undefined = userModelRow?.settings?.extendParams ?? undefined;-- if (modelExtendParams === undefined) {- 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 modelHasReasoningExtendParams = (modelExtendParams ?? []).some((param) =>- (MODEL_REASONING_EXTEND_PARAMS as readonly string[]).includes(param),+ const builtinModels = preloadedModels ?? (await loadModels());+ const cards = createServerModelParamsProviders({ builtinModels });+ return resolveModelExtendParamList(+ { model, provider },+ aiModelModel+ ? {+ ...cards,+ getUserModelRow: async (m, p) => {+ const row = await aiModelModel.findByIdAndProvider(m, p);+ if (!row) return null;+ return {+ abilities: row.abilities,+ displayName: row.displayName,+ extendParams: row.settings?.extendParams ?? undefined,+ };+ },+ }+ : cards,);-- return {- canonicalModelCard,- modelCard,- modelExtendParams,- modelHasReasoningExtendParams,- userModelRow,- };};+/**+ * The model-parameter facts of one LLM attempt. The rules live in+ * `@lobechat/mecha`; this adapter only supplies the server's lookups and the+ * run's frozen snapshots (media capabilities, search decision).+ */export const resolveServerCallLlmContextHints = async ({ctx,llmPayload,@@ -156,208 +95,48 @@ export const resolveServerCallLlmContextHints = async ({world,}: ResolveServerCallLlmContextHintsInput): Promise<ServerCallLlmContextHints> => {const agentConfig = world?.agent;- 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 aiModelModel =- ctx.serverDB && ctx.userId- ? new AiModelModel(ctx.serverDB, ctx.userId, ctx.workspaceId)- : undefined;-- const {- canonicalModelCard,- modelCard,- modelExtendParams,- modelHasReasoningExtendParams,- userModelRow,- } = await resolveModelExtendParamsForUser({ aiModelModel, builtinModels, model, provider });-- const modelKnowledgeCutoff =- modelCard?.knowledgeCutoff ??- (provider === ModelProvider.LobeHub ? canonicalModelCard?.knowledgeCutoff : undefined);- // User-set displayName wins, matching the client list merge- const modelDisplayName =- userModelRow?.displayName ??- modelCard?.displayName ??- (provider === ModelProvider.LobeHub ? canonicalModelCard?.displayName : undefined);-- // Reasoning fields (effort family + reasoningMode) resolve as: topic pin β- // user-level model-instance config (personal scope, cross-workspace).- // Same-named agent chatConfig values are ignored β except explicit sub-agent- // overrides, which stay honored.- //- // The topic pin (`topics.metadata.reasoningConfig`, snapshotted on creation- // and rewritten when the user changes effort / switches model while the- // topic is active) only counts when the topic's pinned model IS the model of- // this attempt: a sub-agent `modelOverride` or a stale snapshot must not- // leak another model's effort. Mirrors the client `modelParamsResolver`.- //- // Only read either source when the model can actually consume it- // (applyModelExtendParams ignores it otherwise) β this runs on every server- // LLM attempt, so non-reasoning models must not pay the extra DB reads.- let modelReasoningConfig: AiModelReasoningConfig | undefined;- if (aiModelModel && modelHasReasoningExtendParams) {- if (ctx.topicId && ctx.serverDB && ctx.userId) {- try {- // Share-visitor runs execute in the owner's context against topics that- // carry a `senderId`; `findById` skips those rows unless opted in, and- // the fallback would silently drop the visitor topic's pin.- const topic = await new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId, undefined, {- includeShareVisitor: true,- }).findById(ctx.topicId);- if (- topic?.model === model &&- topic.provider === provider &&- (!topic.groupId || topic.agentId === agentConfig?.id)- ) {- modelReasoningConfig = topic.metadata?.reasoningConfig;- }- } catch (error) {- log('Failed to resolve topic reasoning pin for %s: %O', ctx.topicId, error);- }- }- if (!modelReasoningConfig) {- try {- modelReasoningConfig = await aiModelModel.getModelReasoningConfig(model, provider);- } catch (error) {- log('Failed to resolve model reasoning config for %s: %O', model, error);- }- }- }-- const agentChatConfig: LobeAgentChatConfig | undefined = agentConfig?.chatConfig;- const subAgentChatConfigOverride: Partial<LobeAgentChatConfig> | undefined =- agentConfig?.subAgentChatConfigOverride ?? undefined;- const effectiveChatConfig =- agentChatConfig || modelReasoningConfig || subAgentChatConfigOverride- ? resolveEffectiveReasoningChatConfig({- agentChatConfig: agentChatConfig ?? {},- modelReasoningConfig,- subAgentReasoningOverrides: subAgentChatConfigOverride,- })- : undefined;-- 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` / `deepseekV4GAReasoningEffort` `'none'`.- // Those flags are V4-specific and may linger on an agent after switching- // models, so they 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) &&- (effectiveChatConfig?.deepseekV4GAReasoningEffort === 'none' ||- effectiveChatConfig?.deepseekV4ReasoningEffort === 'none');- const deepseekForcesPreserveThinking =- isDeepSeekThinkingEligibleModel(model) && !deepseekV4ThinkingDisabled;- /**- * Meta always uses Responses with stateless encrypted reasoning replay. This- * opaque continuation state must survive history building and agent tool loops,- * independently of the user's optional visible-thinking preservation setting.- * The model runtime still validates the replay scope before sending the state.- * @see https://dev.meta.ai/docs/features/responses#reasoning-items- */- const metaForcesPreserveThinking = provider === ModelProvider.Meta;- const modelForcesPreserveThinking =- kimiForcesPreserveThinking || deepseekForcesPreserveThinking || metaForcesPreserveThinking;- 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 resolvedModelExtendParams = effectiveChatConfig- ? applyModelExtendParams({- chatConfig: effectiveChatConfig,- extendParams: modelExtendParams as ExtendParamsType[] | undefined,- model,- })- : undefined;- const searchDecision = world?.searchDecision;- const enabledSearch =- searchDecision?.enabledSearch && searchDecision.useModelSearch ? true : undefined;- const resolvedExtendParams =- resolvedModelExtendParams || enabledSearch- ? {- ...resolvedModelExtendParams,- ...(enabledSearch && { enabledSearch }),- }- : undefined;-- const messagesForContext = shouldReplayAssistantReasoning- ? (llmPayload.messages as UIChatMessage[])- : stripAssistantReasoningForReplay(llmPayload.messages as UIChatMessage[]);-- const findMediaCapabilities = (targetModel: string, targetProvider: string) => {- const snapshot = ctx.modelRuntimeConfig;- // Tool discovery is fixed for the operation; keep native inputs on the same- // snapshot across retries, settings edits, and subsequent worker invocations.- if (- snapshot?.model === targetModel &&- snapshot.provider === targetProvider &&- snapshot.mediaCapabilities- ) {- return snapshot.mediaCapabilities;- }-- // Older operations have no snapshot. Preserve their existing lookup path.- return resolveModelMediaCapabilities({+ const snapshot = ctx.modelRuntimeConfig;++ const resolved = await resolveModelParams(+ {+ agent: {+ chatConfig: agentConfig?.chatConfig,+ id: agentConfig?.id,+ subAgentChatConfigOverride: agentConfig?.subAgentChatConfigOverride,+ },+ // Tool discovery is fixed for the operation; keep native inputs on the+ // same snapshot across retries, settings edits and worker invocations.+ mediaCapabilities:+ snapshot?.model === model && snapshot.provider === provider+ ? snapshot.mediaCapabilities+ : undefined,+ model,+ provider,+ searchDecision: world?.searchDecision,+ topicId: ctx.topicId,+ },+ createServerModelParamsProviders({builtinModels,- model: targetModel,- provider: targetProvider,- // This row belongs only to the active attempt, never to another model/provider.- userAbilities:- targetModel === model && targetProvider === provider ? userModelRow?.abilities : undefined,- });- };+ serverDB: ctx.serverDB,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ const messages = llmPayload.messages as UIChatMessage[];return {- capabilities: {- isCanUseAudio: (targetModel, targetProvider) =>- findMediaCapabilities(targetModel, targetProvider)?.audio ?? false,- isCanUseFC: (targetModel, targetProvider) =>- builtinModels.find((item) => item.id === targetModel && item.providerId === targetProvider)- ?.abilities?.functionCall ?? true,- isCanUseVideo: (targetModel, targetProvider) =>- findMediaCapabilities(targetModel, targetProvider)?.video ?? false,- isCanUseVision: (targetModel, targetProvider) =>- findMediaCapabilities(targetModel, targetProvider)?.vision ?? false,- },- messagesForContext,- modelDisplayName,- modelKnowledgeCutoff,- preserveThinkingForPayload,- resolvedExtendParams,- shouldReplayAssistantReasoning,+ capabilities: resolved.capabilities,+ enableAgentMode: resolved.enableAgentMode,+ historyCount: resolved.historyCount,+ messagesForContext: resolved.shouldReplayAssistantReasoning+ ? messages+ : stripAssistantReasoningForReplay(messages),+ modelDisplayName: resolved.modelDisplayName,+ modelKnowledgeCutoff: resolved.modelKnowledgeCutoff,+ preserveThinkingForPayload: resolved.preserveThinkingForPayload,+ resolvedExtendParams: resolved.resolvedExtendParams,+ shouldReplayAssistantReasoning: resolved.shouldReplayAssistantReasoning,+ stream: resolved.stream,};};diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 722bc7ad3d1..99bd0509c40 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -490,16 +490,6 @@ export const buildServerAgentMemberRunner = (};};-export const resolveRuntimeHistoryCount = (historyCount?: number) => {- if (historyCount === undefined) return undefined;-- // Agent config stores historical message count, excluding the current turn.- // Runtime executors already pass the current user/tool turn in `llmPayload.messages`;- // without this +1, `historyCount: 0` truncates the current message too and sends- // `messages: []` to providers.- return historyCount + 1;-};-export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));export const isOperationInterrupted = async (ctx: RuntimeExecutorContext) => {diff --git a/apps/server/src/modules/Mecha/ModelParams/providers.ts b/apps/server/src/modules/Mecha/ModelParams/providers.tsnew file mode 100644index 00000000000..a0bf3255856--- /dev/null+++ b/apps/server/src/modules/Mecha/ModelParams/providers.ts@@ -0,0 +1,77 @@+import type { LobeChatDatabase } from '@lobechat/database';+import type { ModelCardFacts, ModelParamsProviders } from '@lobechat/mecha';+import type { LobeDefaultAiModelListItem } from 'model-bank';++import { AiModelModel } from '@/database/models/aiModel';+import { TopicModel } from '@/database/models/topic';++export interface ServerModelParamsSource {+ /** Already-loaded model bank; callers on a hot path pass it to avoid a second load. */+ builtinModels: LobeDefaultAiModelListItem[];+ serverDB?: LobeChatDatabase;+ userId?: string;+ workspaceId?: string;+}++const toModelCard = (item: LobeDefaultAiModelListItem): ModelCardFacts => ({+ abilities: item.abilities,+ deploymentName: item.config?.deploymentName,+ displayName: item.displayName,+ extendParams:+ 'settings' in item && item.settings && typeof item.settings === 'object'+ ? ((item.settings as { extendParams?: string[] }).extendParams ?? undefined)+ : undefined,+ id: item.id,+ knowledgeCutoff: item.knowledgeCutoff,+ providerId: item.providerId,+});++/**+ * How the server answers the model-parameter rules: the bundled bank plus,+ * when the run has a user scope, that user's own model row, model-instance+ * reasoning config and the topic's reasoning pin.+ */+export const createServerModelParamsProviders = ({+ builtinModels,+ serverDB,+ userId,+ workspaceId,+}: ServerModelParamsSource): ModelParamsProviders => {+ const cards = builtinModels.map(toModelCard);+ const providers: ModelParamsProviders = { listModelCards: () => cards };+ if (!serverDB || !userId) return providers;++ const aiModelModel = new AiModelModel(serverDB, userId, workspaceId);+ return {+ ...providers,+ // Share-visitor runs execute in the owner's context against topics that+ // carry a `senderId`; `findById` skips those rows unless opted in, and+ // the fallback would silently drop the visitor topic's pin.+ findTopicReasoningPin: async (topicId) => {+ const topic = await new TopicModel(serverDB, userId, workspaceId, undefined, {+ includeShareVisitor: true,+ }).findById(topicId);+ if (!topic) return null;+ return {+ agentId: topic.agentId,+ groupId: topic.groupId,+ model: topic.model,+ provider: topic.provider,+ reasoningConfig: topic.metadata?.reasoningConfig,+ };+ },+ getModelReasoningConfig: (model, provider) =>+ aiModelModel.getModelReasoningConfig(model, provider),+ // The user's own AI model row: custom/remote models miss both bundled+ // cards entirely, and builtin models may carry user-edited settings.+ getUserModelRow: async (model, provider) => {+ const row = await aiModelModel.findByIdAndProvider(model, provider);+ if (!row) return null;+ return {+ abilities: row.abilities,+ displayName: row.displayName,+ extendParams: row.settings?.extendParams ?? undefined,+ };+ },+ };+};diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.tsindex af825897218..56f1eebabc3 100644--- a/packages/agent-runtime/src/executors/callLlm.test.ts+++ b/packages/agent-runtime/src/executors/callLlm.test.ts@@ -224,6 +224,8 @@ describe('callLlm executor', () => {});expect(transport.createTrace).toHaveBeenCalledWith({assistantMessageId: 'assistant-1',+ // The built context rides along so the trace records what the request carries.+ context: expect.objectContaining({ messages: [{ content: 'prepared hello', role: 'user' }] }),conversationId: 'topic-1',model: 'gpt-4',provider: 'openai',diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.tsindex a39fee25671..cefbbe478f7 100644--- a/packages/agent-runtime/src/executors/callLlm.ts+++ b/packages/agent-runtime/src/executors/callLlm.ts@@ -391,6 +391,7 @@ export const callLlm =assertPreparedCallContext(prepared, operation.stepIndex);const trace = llm.createTrace?.({assistantMessageId: assistantMessage.id,+ context,conversationId: state.origin?.topicId,model,provider,diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.tsindex 14ee64689ec..3d8ec4852d6 100644--- a/packages/agent-runtime/src/transport/llm.ts+++ b/packages/agent-runtime/src/transport/llm.ts@@ -105,6 +105,8 @@ export interface LLMRetryPolicy {export interface LLMTraceInput {assistantMessageId: string;+ /** The built context this call sends, so a trace can record what the request really carries. */+ context?: ContextBuildOutput;conversationId?: string;model: string;provider: string;diff --git a/packages/mecha/package.json b/packages/mecha/package.jsonindex 530b9d122bc..399b8926b00 100644--- a/packages/mecha/package.json+++ b/packages/mecha/package.json@@ -21,12 +21,15 @@"@lobechat/builtin-tool-task": "workspace:*","@lobechat/builtin-tool-web-onboarding": "workspace:*","@lobechat/builtin-tools": "workspace:*",+ "@lobechat/business-const": "workspace:*","@lobechat/const": "workspace:*","@lobechat/context-engine": "workspace:*",+ "@lobechat/model-runtime": "workspace:*","@lobechat/prompts": "workspace:*","@lobechat/types": "workspace:*","debug": "^4.4.3","immer": "^10.1.3",+ "model-bank": "workspace:*","p-map": "^7.0.6"}}diff --git a/packages/mecha/src/index.ts b/packages/mecha/src/index.tsindex 33789466c35..23100f876f5 100644--- a/packages/mecha/src/index.ts+++ b/packages/mecha/src/index.ts@@ -1,4 +1,5 @@export * from './contextEngineering';+export * from './modelParams';export type {AgentConfigResolverContext,AgentConfigSnapshot,diff --git a/packages/mecha/src/modelParams/index.ts b/packages/mecha/src/modelParams/index.tsnew file mode 100644index 00000000000..92a2c7995ed--- /dev/null+++ b/packages/mecha/src/modelParams/index.ts@@ -0,0 +1,6 @@+export {+ resolveHistoryCount,+ resolveModelExtendParamList,+ resolveModelParams,+} from './resolveModelParams';+export type * from './types';diff --git a/packages/mecha/src/modelParams/resolveModelParams.test.ts b/packages/mecha/src/modelParams/resolveModelParams.test.tsnew file mode 100644index 00000000000..1aad55e7703--- /dev/null+++ b/packages/mecha/src/modelParams/resolveModelParams.test.ts@@ -0,0 +1,314 @@+import { describe, expect, it, vi } from 'vitest';++import { resolveHistoryCount, resolveModelParams } from './resolveModelParams';+import type { ModelCardFacts, ModelParamsProviders, ModelParamsRequest } from './types';++const cards: ModelCardFacts[] = [+ {+ abilities: { functionCall: true, vision: true },+ displayName: 'GPT-4',+ extendParams: ['reasoningEffort'],+ id: 'gpt-4',+ knowledgeCutoff: '2024-01',+ providerId: 'openai',+ },+ {+ abilities: {},+ displayName: 'DeepSeek V4 Pro',+ extendParams: ['deepseekV4ReasoningEffort'],+ id: 'deepseek-v4-pro',+ providerId: 'deepseek',+ },+ { abilities: { functionCall: false }, displayName: 'Plain', id: 'plain', providerId: 'openai' },+ {+ abilities: { vision: true },+ displayName: 'GPT-4 (hub)',+ extendParams: ['reasoningEffort'],+ id: 'gpt-4',+ knowledgeCutoff: '2024-01',+ providerId: 'lobehub',+ },+];++const providers = (overrides: Partial<ModelParamsProviders> = {}): ModelParamsProviders => ({+ listModelCards: () => cards,+ ...overrides,+});++const request = (overrides: Partial<ModelParamsRequest> = {}): ModelParamsRequest => ({+ agent: { chatConfig: {}, id: 'agt_1' },+ model: 'gpt-4',+ provider: 'openai',+ topicId: 'tpc_1',+ ...overrides,+});++describe('resolveModelParams', () => {+ describe('extend params', () => {+ it('lets the user row win, treats an emptied row as an opt-out and falls back to the cards', async () => {+ const own = await resolveModelParams(+ request(),+ providers({ getUserModelRow: async () => ({ extendParams: ['thinking'] }) }),+ );+ expect(own.modelExtendParams).toEqual(['thinking']);+ expect(own.modelHasReasoningExtendParams).toBe(false);++ const optedOut = await resolveModelParams(+ request(),+ providers({ getUserModelRow: async () => ({ extendParams: [] }) }),+ );+ expect(optedOut.modelExtendParams).toEqual([]);++ const fromCard = await resolveModelParams(request(), providers());+ expect(fromCard.modelExtendParams).toEqual(['reasoningEffort']);+ expect(fromCard.modelHasReasoningExtendParams).toBe(true);+ });++ it('falls back to the canonical card for an aggregation provider', async () => {+ const facts = await resolveModelParams(+ request({ provider: 'lobehub' }),+ providers({+ listModelCards: () => [{ ...cards[3], extendParams: undefined }, cards[0]],+ }),+ );+ expect(facts.modelExtendParams).toEqual(['reasoningEffort']);+ expect(facts.modelKnowledgeCutoff).toBe('2024-01');+ });++ it('applies the effective config to the payload params', async () => {+ const facts = await resolveModelParams(+ request(),+ providers({ getModelReasoningConfig: async () => ({ reasoningEffort: 'high' }) }),+ );+ expect(facts.resolvedExtendParams).toMatchObject({ reasoning_effort: 'high' });+ });+ });++ describe('reasoning config precedence', () => {+ it('lets the topic pin win over the model-instance config', async () => {+ const facts = await resolveModelParams(+ request(),+ providers({+ findTopicReasoningPin: async () => ({+ model: 'gpt-4',+ provider: 'openai',+ reasoningConfig: { reasoningEffort: 'low' },+ }),+ getModelReasoningConfig: async () => ({ reasoningEffort: 'high' }),+ }),+ );+ expect(facts.resolvedExtendParams).toMatchObject({ reasoning_effort: 'low' });+ });++ it('ignores a pin taken for another model or, in a group topic, for another agent', async () => {+ const getModelReasoningConfig = vi.fn(async () => ({ reasoningEffort: 'high' as const }));+ const otherModel = await resolveModelParams(+ request(),+ providers({+ findTopicReasoningPin: async () => ({+ model: 'gpt-4o',+ provider: 'openai',+ reasoningConfig: { reasoningEffort: 'low' },+ }),+ getModelReasoningConfig,+ }),+ );+ expect(otherModel.resolvedExtendParams).toMatchObject({ reasoning_effort: 'high' });++ const otherAgent = await resolveModelParams(+ request(),+ providers({+ findTopicReasoningPin: async () => ({+ agentId: 'agt_2',+ groupId: 'grp_1',+ model: 'gpt-4',+ provider: 'openai',+ reasoningConfig: { reasoningEffort: 'low' },+ }),+ getModelReasoningConfig,+ }),+ );+ expect(otherAgent.resolvedExtendParams).toMatchObject({ reasoning_effort: 'high' });+ });++ it('treats an empty pin as the defaults but a legacy topic without one as unpinned', async () => {+ const getModelReasoningConfig = vi.fn(async () => ({ reasoningEffort: 'low' as const }));+ const pinned = await resolveModelParams(+ request(),+ providers({+ findTopicReasoningPin: async () => ({+ model: 'gpt-4',+ provider: 'openai',+ reasoningConfig: {},+ }),+ getModelReasoningConfig,+ }),+ );+ expect(getModelReasoningConfig).not.toHaveBeenCalled();+ expect(pinned.resolvedExtendParams).toEqual({});++ const legacy = await resolveModelParams(+ request(),+ providers({+ findTopicReasoningPin: async () => ({ model: 'gpt-4', provider: 'openai' }),+ getModelReasoningConfig,+ }),+ );+ expect(legacy.resolvedExtendParams).toMatchObject({ reasoning_effort: 'low' });+ });++ it('does not read either source for a model without reasoning extend params', async () => {+ const findTopicReasoningPin = vi.fn();+ const getModelReasoningConfig = vi.fn();+ await resolveModelParams(+ request({ model: 'plain' }),+ providers({ findTopicReasoningPin, getModelReasoningConfig }),+ );+ expect(findTopicReasoningPin).not.toHaveBeenCalled();+ expect(getModelReasoningConfig).not.toHaveBeenCalled();+ });++ it('lets explicit sub-agent overrides win over the instance config', async () => {+ const facts = await resolveModelParams(+ request({+ agent: { chatConfig: {}, subAgentChatConfigOverride: { reasoningEffort: 'low' } },+ }),+ providers({ getModelReasoningConfig: async () => ({ reasoningEffort: 'high' }) }),+ );+ expect(facts.resolvedExtendParams).toMatchObject({ reasoning_effort: 'low' });+ });+ });++ describe('assistant reasoning replay', () => {+ it('replays only when configured and supported by the card', async () => {+ const off = await resolveModelParams(request(), providers());+ expect(off.shouldReplayAssistantReasoning).toBe(false);+ expect(off.preserveThinkingForPayload).toBeUndefined();++ const withCard = providers({+ listModelCards: () => [{ ...cards[0], extendParams: ['preserveThinking'] }],+ });+ const on = await resolveModelParams(+ request({ agent: { chatConfig: { preserveThinking: true } } }),+ withCard,+ );+ expect(on.shouldReplayAssistantReasoning).toBe(true);+ expect(on.preserveThinkingForPayload).toBe(true);++ const declined = await resolveModelParams(+ request({ agent: { chatConfig: { preserveThinking: false } } }),+ withCard,+ );+ expect(declined.shouldReplayAssistantReasoning).toBe(false);+ expect(declined.preserveThinkingForPayload).toBe(false);+ });++ it('forces replay for DeepSeek thinking models unless V4 thinking is disabled', async () => {+ const forced = await resolveModelParams(+ request({ model: 'deepseek-v4-pro', provider: 'deepseek' }),+ providers(),+ );+ expect(forced.shouldReplayAssistantReasoning).toBe(true);+ expect(forced.preserveThinkingForPayload).toBe(true);++ const disabled = await resolveModelParams(+ request({ model: 'deepseek-v4-pro', provider: 'deepseek' }),+ providers({+ getModelReasoningConfig: async () => ({ deepseekV4ReasoningEffort: 'none' }),+ }),+ );+ expect(disabled.shouldReplayAssistantReasoning).toBe(false);+ });++ it('forces replay for Meta and falls back to the provider for an unknown qwen model', async () => {+ const meta = await resolveModelParams(+ request({ model: 'llama-x', provider: 'meta' }),+ providers(),+ );+ expect(meta.shouldReplayAssistantReasoning).toBe(true);++ const qwen = await resolveModelParams(+ request({+ agent: { chatConfig: { preserveThinking: true } },+ model: 'qwen-unknown',+ provider: 'qwen',+ }),+ providers(),+ );+ expect(qwen.shouldReplayAssistantReasoning).toBe(true);+ });+ });++ describe('capabilities', () => {+ it('prefers the frozen snapshot, then the user row, then the cards', async () => {+ const snapshot = await resolveModelParams(+ request({ mediaCapabilities: { vision: false } }),+ providers({ getUserModelRow: async () => ({ abilities: { vision: true } }) }),+ );+ expect(snapshot.capabilities.isCanUseVision('gpt-4', 'openai')).toBe(false);+ // The snapshot never applies to another model.+ expect(snapshot.capabilities.isCanUseVision('gpt-4', 'lobehub')).toBe(true);++ const row = await resolveModelParams(+ request(),+ providers({ getUserModelRow: async () => ({ abilities: { vision: false } }) }),+ );+ expect(row.capabilities.isCanUseVision('gpt-4', 'openai')).toBe(false);++ const card = await resolveModelParams(request(), providers());+ expect(card.capabilities.isCanUseVision('gpt-4', 'openai')).toBe(true);+ expect(card.capabilities.isCanUseAudio('gpt-4', 'openai')).toBe(false);+ });++ it('assumes function calling for an unknown model and honors an explicit false', async () => {+ const facts = await resolveModelParams(request(), providers());+ expect(facts.capabilities.isCanUseFC('unknown', 'openai')).toBe(true);+ expect(facts.capabilities.isCanUseFC('plain', 'openai')).toBe(false);+ });+ });++ describe('chat config passthrough', () => {+ it('keeps the stored agent mode, reads stream and the history window from the config', async () => {+ const facts = await resolveModelParams(+ request({+ agent: {+ chatConfig: { enableAgentMode: true, enableStreaming: false, historyCount: 0 },+ },+ model: 'plain',+ }),+ providers(),+ );+ // A model without function calling does not demote the agent mode.+ expect(facts.enableAgentMode).toBe(true);+ expect(facts.stream).toBe(false);+ expect(facts.historyCount).toBe(1);++ const defaults = await resolveModelParams(request({ agent: {} }), providers());+ expect(defaults.enableAgentMode).toBeUndefined();+ expect(defaults.stream).toBe(true);+ expect(defaults.historyCount).toBeUndefined();+ });++ it('emits enabledSearch only when the decision enables model search', async () => {+ const on = await resolveModelParams(+ request({ searchDecision: { enabledSearch: true, useModelSearch: true } }),+ providers(),+ );+ expect(on.resolvedExtendParams).toMatchObject({ enabledSearch: true });+ const off = await resolveModelParams(+ request({ searchDecision: { enabledSearch: true, useModelSearch: false } }),+ providers(),+ );+ expect(off.resolvedExtendParams?.enabledSearch).toBeUndefined();+ });+ });+});++describe('resolveHistoryCount', () => {+ it('adds the current turn and leaves unset alone', () => {+ expect(resolveHistoryCount(0)).toBe(1);+ expect(resolveHistoryCount(20)).toBe(21);+ expect(resolveHistoryCount(undefined)).toBeUndefined();+ expect(resolveHistoryCount(null)).toBeUndefined();+ });+});diff --git a/packages/mecha/src/modelParams/resolveModelParams.ts b/packages/mecha/src/modelParams/resolveModelParams.tsnew file mode 100644index 00000000000..af1ab3f1936--- /dev/null+++ b/packages/mecha/src/modelParams/resolveModelParams.ts@@ -0,0 +1,285 @@+import { BRANDING_PROVIDER } from '@lobechat/business-const/branding';+import {+ isDeepSeekThinkingEligibleModel,+ isDeepSeekV4FamilyModel,+} from '@lobechat/model-runtime/providers/deepseek/modelId';+import { isKimiAlwaysPreserveThinkingModel } from '@lobechat/model-runtime/providers/moonshot/modelId';+import {+ applyModelExtendParams,+ resolveEffectiveReasoningChatConfig,+} from '@lobechat/model-runtime/utils/modelExtendParams';+import type { LobeAgentChatConfig } from '@lobechat/types';+import debug from 'debug';+import {+ type AiModelReasoningConfig,+ type ExtendParamsType,+ MODEL_REASONING_EXTEND_PARAMS,+} from 'model-bank';+import { ModelProvider } from 'model-bank/modelProvider';++import type {+ MediaCapabilities,+ ModelCardFacts,+ ModelParamsProviders,+ ModelParamsRequest,+ ResolvedModelExtendParamList,+ ResolvedModelParams,+} from './types';++const log = debug('mecha:modelParams');++const REASONING_EXTEND_PARAMS = MODEL_REASONING_EXTEND_PARAMS as readonly string[];++const attempt = async <T>(+ label: string,+ run: () => Promise<T | null | undefined> | T | null | undefined,+): Promise<T | undefined> => {+ try {+ return (await run()) ?? undefined;+ } catch (error) {+ log('%s failed (non-fatal): %O', label, error);+ return undefined;+ }+};++const matchesModel = (card: ModelCardFacts, model: string) =>+ card.id === model || card.deploymentName === model;++/**+ * Agent config stores the number of history messages, excluding the current+ * turn. The runtime already carries the current user / tool turn, so without+ * the +1 a `historyCount` of 0 would truncate the current message too. An+ * unset value means no truncation at all.+ */+export const resolveHistoryCount = (historyCount?: number | null): number | undefined =>+ typeof historyCount === 'number' ? historyCount + 1 : undefined;++/**+ * Which extend params the model can consume for this user: the user's own+ * row (an explicit empty array opts out), else the provider's card, else the+ * canonical card matched by id across providers β aggregation providers may+ * serve a model without copying its origin `settings.extendParams`.+ */+export const resolveModelExtendParamList = async (+ request: Pick<ModelParamsRequest, 'model' | 'provider'>,+ providers: ModelParamsProviders,+): Promise<ResolvedModelExtendParamList> => {+ const { model, provider } = request;+ const cards = providers.listModelCards();+ const modelCard = cards.find((card) => card.providerId === provider && matchesModel(card, model));+ // The origin card of the same model under another provider; aggregation+ // providers may serve it without copying its settings.+ const canonicalModelCard =+ cards.find((card) => card.providerId !== provider && matchesModel(card, model)) ??+ cards.find((card) => matchesModel(card, model));+ const userModelRow = await attempt('userModelRow', () =>+ providers.getUserModelRow?.(model, provider),+ );++ let modelExtendParams = userModelRow?.extendParams ?? undefined;+ if (modelExtendParams === undefined) {+ modelExtendParams = modelCard?.extendParams ?? undefined;+ if (!modelExtendParams || modelExtendParams.length === 0) {+ modelExtendParams = canonicalModelCard?.extendParams ?? undefined;+ }+ }++ return {+ canonicalModelCard,+ modelCard,+ modelExtendParams,+ modelHasReasoningExtendParams: (modelExtendParams ?? []).some((param) =>+ REASONING_EXTEND_PARAMS.includes(param),+ ),+ userModelRow,+ };+};++/**+ * Reasoning fields resolve as: topic pin β user-level model-instance config.+ * The pin only counts when the topic pinned exactly this model (a sub-agent+ * `modelOverride` or a stale snapshot must not leak another model's effort)+ * and, in a group topic, when it belongs to the agent that is answering.+ */+const resolveReasoningConfig = async (+ request: ModelParamsRequest,+ providers: ModelParamsProviders,+): Promise<AiModelReasoningConfig | undefined> => {+ const { model, provider, topicId } = request;+ if (topicId && providers.findTopicReasoningPin) {+ const { findTopicReasoningPin } = providers;+ const pin = await attempt('topicReasoningPin', () => findTopicReasoningPin(topicId));+ // An empty pin is a pin (the model defaults); a legacy topic without one+ // follows the user-level config until the user pins something.+ if (+ pin?.model === model &&+ pin.provider === provider &&+ (!pin.groupId || pin.agentId === request.agent.id) &&+ pin.reasoningConfig+ ) {+ return pin.reasoningConfig;+ }+ }+ return attempt('modelReasoningConfig', () =>+ providers.getModelReasoningConfig?.(model, provider),+ );+};++const isNonEmptyRecord = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;++/**+ * Decide the model parameters of an LLM call from the agent's chat config,+ * the model's cards and the user's per-model settings. The rules β what a+ * model can consume, where reasoning effort comes from, when assistant+ * reasoning must be replayed, what capabilities the context may assume β+ * live here for every host; hosts only answer the lookups.+ */+export const resolveModelParams = async (+ request: ModelParamsRequest,+ providers: ModelParamsProviders,+): Promise<ResolvedModelParams> => {+ const { model, provider } = request;+ const chatConfig: LobeAgentChatConfig | undefined = request.agent.chatConfig ?? undefined;+ const extendParamList = await resolveModelExtendParamList(request, providers);+ const {+ canonicalModelCard,+ modelCard,+ modelExtendParams,+ modelHasReasoningExtendParams,+ userModelRow,+ } = extendParamList;++ const modelKnowledgeCutoff =+ modelCard?.knowledgeCutoff ??+ (provider === ModelProvider.LobeHub ? canonicalModelCard?.knowledgeCutoff : undefined) ??+ undefined;+ // A user-set display name wins, matching the client list merge.+ const modelDisplayName =+ userModelRow?.displayName ??+ modelCard?.displayName ??+ (provider === ModelProvider.LobeHub ? canonicalModelCard?.displayName : undefined) ??+ undefined;++ // Only read the reasoning sources when the model can actually consume them+ // (`applyModelExtendParams` ignores them otherwise) β this runs on every+ // LLM attempt, so non-reasoning models must not pay the extra reads.+ const modelReasoningConfig = modelHasReasoningExtendParams+ ? await resolveReasoningConfig(request, providers)+ : undefined;++ const subAgentChatConfigOverride = request.agent.subAgentChatConfigOverride ?? undefined;+ const effectiveChatConfig =+ chatConfig || modelReasoningConfig || subAgentChatConfigOverride+ ? resolveEffectiveReasoningChatConfig({+ agentChatConfig: chatConfig ?? {},+ modelReasoningConfig,+ subAgentReasoningOverrides: subAgentChatConfigOverride,+ })+ : undefined;++ const preserveThinkingConfigured =+ typeof chatConfig?.preserveThinking === 'boolean' ? chatConfig.preserveThinking : undefined;+ 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: their Anthropic-compatible API rejects an assistant tool-call+ // turn whose thinking block is missing, and a placeholder block makes the+ // model answer inside its thinking. The only opt-out is a V4 model whose+ // thinking the user explicitly disabled; those flags are V4-specific and+ // must not suppress replay for the thinking-only `deepseek-reasoner`.+ const deepseekV4ThinkingDisabled =+ isDeepSeekV4FamilyModel(model) &&+ (effectiveChatConfig?.deepseekV4GAReasoningEffort === 'none' ||+ effectiveChatConfig?.deepseekV4ReasoningEffort === 'none');+ const deepseekForcesPreserveThinking =+ isDeepSeekThinkingEligibleModel(model) && !deepseekV4ThinkingDisabled;+ // Meta always uses Responses with stateless encrypted reasoning replay; the+ // opaque continuation state must survive history building and tool loops+ // independently of the user's visible-thinking preference.+ const metaForcesPreserveThinking = provider === ModelProvider.Meta;+ const modelForcesPreserveThinking =+ kimiForcesPreserveThinking || deepseekForcesPreserveThinking || metaForcesPreserveThinking;+ const providerSupportsPreserveThinkingFallback =+ provider === 'qwen' || provider === 'zhipu' || provider === 'moonshot';+ const modelSupportsPreserveThinking =+ modelForcesPreserveThinking ||+ modelSupportsPreserveThinkingFromCard ||+ (!modelCard && providerSupportsPreserveThinkingFallback);++ const shouldReplayAssistantReasoning =+ (modelForcesPreserveThinking || preserveThinkingConfigured === true) &&+ modelSupportsPreserveThinking;+ const preserveThinkingForPayload = modelForcesPreserveThinking+ ? true+ : modelSupportsPreserveThinking && typeof preserveThinkingConfigured === 'boolean'+ ? preserveThinkingConfigured+ : undefined;++ const resolvedModelExtendParams = effectiveChatConfig+ ? applyModelExtendParams({+ chatConfig: effectiveChatConfig,+ extendParams: modelExtendParams as ExtendParamsType[] | undefined,+ model,+ })+ : undefined;+ const { searchDecision } = request;+ const enabledSearch =+ searchDecision?.enabledSearch && searchDecision.useModelSearch ? true : undefined;+ const resolvedExtendParams =+ resolvedModelExtendParams || enabledSearch+ ? { ...resolvedModelExtendParams, ...(enabledSearch && { enabledSearch }) }+ : undefined;++ const cards = providers.listModelCards();+ const findCard = (targetModel: string, targetProvider: string) =>+ cards.find((card) => card.providerId === targetProvider && matchesModel(card, targetModel));+ // A non-empty user abilities object replaces the card's abilities, explicit+ // false values included; media routing and context assembly must agree or+ // native attachments are discarded.+ const findMediaCapabilities = (+ targetModel: string,+ targetProvider: string,+ ): MediaCapabilities | undefined => {+ const isAttemptModel = targetModel === model && targetProvider === provider;+ if (isAttemptModel && request.mediaCapabilities) return request.mediaCapabilities;+ const userAbilities = isAttemptModel ? userModelRow?.abilities : undefined;+ if (isNonEmptyRecord(userAbilities)) {+ return {+ audio: userAbilities.audio === true,+ video: userAbilities.video === true,+ vision: userAbilities.vision === true,+ };+ }+ return (+ (+ findCard(targetModel, targetProvider) ??+ cards.find((card) => matchesModel(card, targetModel))+ )?.abilities ?? undefined+ );+ };++ return {+ ...extendParamList,+ capabilities: {+ isCanUseAudio: (m, p) => findMediaCapabilities(m, p)?.audio ?? false,+ // Unknown metadata means "assume function calling": a missing card is a+ // timing or custom-model gap, not a capability statement.+ isCanUseFC: (m, p) => findCard(m, p)?.abilities?.functionCall ?? true,+ isCanUseVideo: (m, p) => findMediaCapabilities(m, p)?.video ?? false,+ isCanUseVision: (m, p) => findMediaCapabilities(m, p)?.vision ?? false,+ },+ enableAgentMode: chatConfig?.enableAgentMode ?? undefined,+ historyCount: resolveHistoryCount(chatConfig?.historyCount),+ modelDisplayName,+ modelKnowledgeCutoff,+ preserveThinkingForPayload,+ resolvedExtendParams,+ shouldReplayAssistantReasoning,+ stream: chatConfig?.enableStreaming !== false,+ };+};diff --git a/packages/mecha/src/modelParams/types.ts b/packages/mecha/src/modelParams/types.tsnew file mode 100644index 00000000000..0dc9df40689--- /dev/null+++ b/packages/mecha/src/modelParams/types.ts@@ -0,0 +1,108 @@+import type { ModelExtendParams } from '@lobechat/model-runtime/utils/modelExtendParams';+import type { LobeAgentChatConfig } from '@lobechat/types';+import type { AiModelReasoningConfig, ModelAbilities } from 'model-bank';++/** The subset of a model card the rules read (bundled bank or user-enabled list). */+export interface ModelCardFacts {+ abilities?: ModelAbilities | null;+ /** Deployment alias some providers address the model by. */+ deploymentName?: string | null;+ displayName?: string | null;+ extendParams?: string[] | null;+ id: string;+ knowledgeCutoff?: string | null;+ providerId: string;+}++/** The user's own row for the model, when they edited or created one. */+export interface UserModelRowFacts {+ /** Stored as untyped JSON; a non-empty object replaces the card's abilities. */+ abilities?: unknown;+ displayName?: string | null;+ /** `[]` is an explicit opt-out from the card's params; absent falls back to the cards. */+ extendParams?: string[] | null;+}++/** The reasoning config a topic pinned at creation, with the model it was pinned for. */+export interface TopicReasoningPinFacts {+ agentId?: string | null;+ groupId?: string | null;+ model?: string | null;+ provider?: string | null;+ reasoningConfig?: AiModelReasoningConfig | null;+}++export type MediaCapabilities = Pick<ModelAbilities, 'audio' | 'video' | 'vision'>;++/** Everything the model-parameter rules read about the run. */+export interface ModelParamsRequest {+ agent: {+ chatConfig?: LobeAgentChatConfig | null;+ id?: string;+ /** Raw sub-agent chatConfig patch; explicit reasoning fields here win. */+ subAgentChatConfigOverride?: Partial<LobeAgentChatConfig> | null;+ };+ /**+ * Media capabilities frozen when the operation was created, for exactly+ * `model` / `provider`. Preferred over a live lookup so retries and settings+ * edits cannot change what the run already discovered.+ */+ mediaCapabilities?: MediaCapabilities;+ model: string;+ provider: string;+ searchDecision?: { enabledSearch?: boolean; useModelSearch?: boolean };+ topicId?: string;+}++/**+ * How a host fetches model facts. Cards are synchronous (both hosts hold the+ * bank in memory); the user row, the reasoning config and the topic pin are+ * lookups the rules only make when the model can consume the result.+ */+export interface ModelParamsProviders {+ /** The topic's reasoning pin. Share-visitor topics must be readable too. */+ findTopicReasoningPin?: (topicId: string) => Promise<TopicReasoningPinFacts | null | undefined>;+ /** The user's model-instance reasoning config (personal scope). */+ getModelReasoningConfig?: (+ model: string,+ provider: string,+ ) => Promise<AiModelReasoningConfig | null | undefined>;+ getUserModelRow?: (+ model: string,+ provider: string,+ ) => Promise<UserModelRowFacts | null | undefined>;+ /** Every model card the host knows; the rules match by provider / id / deployment name. */+ listModelCards: () => ModelCardFacts[];+}++export interface ResolvedModelExtendParamList {+ /** Card matched by id across any provider (aggregation fallback). */+ canonicalModelCard?: ModelCardFacts;+ /** Card for exactly `provider` / `model`. */+ modelCard?: ModelCardFacts;+ /** Effective extend params: user row β provider card β canonical card. */+ modelExtendParams?: string[];+ /** True when any effort-family / reasoningMode param is among `modelExtendParams`. */+ modelHasReasoningExtendParams: boolean;+ userModelRow?: UserModelRowFacts;+}++export interface ResolvedModelParams extends ResolvedModelExtendParamList {+ 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;+ };+ /** The agent's stored mode, untouched: a model without function calling keeps it. */+ enableAgentMode?: boolean;+ /** History window incl. the current turn; undefined = no truncation. */+ historyCount?: number;+ modelDisplayName?: string;+ modelKnowledgeCutoff?: string;+ preserveThinkingForPayload?: boolean;+ resolvedExtendParams?: ModelExtendParams & { enabledSearch?: boolean };+ shouldReplayAssistantReasoning: boolean;+ /** Whether the LLM call streams, from the agent's chat config. */+ stream: boolean;+}diff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.jsonindex 587f05514b2..c8c59be0519 100644--- a/packages/model-runtime/package.json+++ b/packages/model-runtime/package.json@@ -9,6 +9,8 @@"./getModelPropertyWithFallback": "./src/utils/getFallbackModelProperty.ts","./helpers/parseToolCalls": "./src/helpers/parseToolCalls.ts","./providers/anthropic/modelId": "./src/providers/anthropic/modelId.ts",+ "./providers/deepseek/modelId": "./src/providers/deepseek/modelId.ts",+ "./providers/moonshot/modelId": "./src/providers/moonshot/modelId.ts","./providers/openai/modelId": "./src/providers/openai/modelId.ts","./resolveImageSinglePrice": "./src/core/usageConverters/utils/resolveImageSinglePrice.ts","./resolveVideoSinglePrice": "./src/core/usageConverters/utils/resolveVideoSinglePrice.ts",diff --git a/packages/model-runtime/src/providers/deepseek/modelId.ts b/packages/model-runtime/src/providers/deepseek/modelId.tsnew file mode 100644index 00000000000..43299df2ee2--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/modelId.ts@@ -0,0 +1,13 @@+/**+ * DeepSeek model-id predicates. Kept dependency-free so callers outside the+ * runtime (the shared `@lobechat/mecha` rules) can import them without+ * pulling the model bank in.+ */+export const isDeepSeekV4FamilyModel = (model: string | undefined): boolean =>+ typeof model === 'string' &&+ (model.toLowerCase().includes('deepseek-v4') ||+ model.toLowerCase().split('/').at(-1) === 'deepseek-flash');++export const isDeepSeekThinkingEligibleModel = (model: string | undefined): boolean =>+ typeof model === 'string' &&+ (model.toLowerCase().includes('deepseek-reasoner') || isDeepSeekV4FamilyModel(model));diff --git a/packages/model-runtime/src/utils/modelParse.ts b/packages/model-runtime/src/utils/modelParse.tsindex f7350e84f3c..36b1e913318 100644--- a/packages/model-runtime/src/utils/modelParse.ts+++ b/packages/model-runtime/src/utils/modelParse.ts@@ -193,14 +193,10 @@ export const MODEL_OWNER_DETECTION_CONFIG = {zhipu: ['glm'],} as const;-export const isDeepSeekV4FamilyModel = (model: string | undefined): boolean =>- typeof model === 'string' &&- (model.toLowerCase().includes('deepseek-v4') ||- model.toLowerCase().split('/').at(-1) === 'deepseek-flash');--export const isDeepSeekThinkingEligibleModel = (model: string | undefined): boolean =>- typeof model === 'string' &&- (model.toLowerCase().includes('deepseek-reasoner') || isDeepSeekV4FamilyModel(model));+export {+ isDeepSeekThinkingEligibleModel,+ isDeepSeekV4FamilyModel,+} from '../providers/deepseek/modelId';// Image model keyword configurationexport const IMAGE_MODEL_KEYWORDS = [