Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚑️ perf(agent): freeze a run's model facts on the operation (#19698)

Arvin Xu0430bca287e4
diff --git a/.agents/skills/add-model-provider/references/integration-map.md b/.agents/skills/add-model-provider/references/integration-map.md
index 4b8a69e3f9c..0920f3e8eea 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`, `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 |
+| 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. A server run resolves the params from the `modelRuntimeConfig.modelFacts` snapshot frozen once in `toolDiscovery.ts`, so a new source the rules must read has to be added to `readFrozenModelFacts` as well, or it stays unread on every step |
+| 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/serverCallLlmContextHints.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
index c3093608b05..4e71609d7f8 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
@@ -1,8 +1,11 @@
import type { CallLLMPayload } from '@lobechat/agent-runtime';
import { MessagesEngine } from '@lobechat/context-engine';
+import { readFrozenModelFacts } from '@lobechat/mecha';
import type { UIChatMessage } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createServerModelParamsProviders } from '@/server/modules/Mecha/ModelParams/providers';
+
import type { RuntimeExecutorContext } from '../context';
import { resolveServerCallLlmContextHints } from './serverCallLlmContextHints';
@@ -669,3 +672,131 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
});
});
+
+describe('resolveServerCallLlmContextHints - frozen operation facts', () => {
+ const frozenCtx = (): RuntimeExecutorContext => ({
+ ...createCtx(),
+ modelRuntimeConfig: {
+ mediaCapabilities: { vision: true },
+ modelFacts: {
+ cards: [
+ {
+ abilities: { functionCall: true, vision: true },
+ displayName: 'GPT-4 (frozen)',
+ extendParams: ['reasoningEffort'],
+ id: 'gpt-4',
+ knowledgeCutoff: '2024-01',
+ providerId: 'openai',
+ },
+ ],
+ mediaCapabilities: { vision: true },
+ model: 'gpt-4',
+ provider: 'openai',
+ reasoningConfig: { reasoningEffort: 'low' },
+ },
+ model: 'gpt-4',
+ provider: 'openai',
+ topicId: undefined,
+ } as RuntimeExecutorContext['modelRuntimeConfig'],
+ topicId: 'tpc_1',
+ });
+
+ it('reads no model source on a step and keeps the effort the run started with', async () => {
+ // What the user changed after the run started β€” none of it may be read.
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
+ findTopicByIdMock.mockResolvedValue({
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: frozenCtx(),
+ world: { agent: { chatConfig: {} } },
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(hints.resolvedExtendParams).toMatchObject({ reasoning_effort: 'low' });
+ expect(hints.modelDisplayName).toBe('GPT-4 (frozen)');
+ expect(hints.capabilities.isCanUseVision('gpt-4', 'openai')).toBe(true);
+ expect(loadModelsMock).not.toHaveBeenCalled();
+ expect(findByIdAndProviderMock).not.toHaveBeenCalled();
+ expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
+ expect(findTopicByIdMock).not.toHaveBeenCalled();
+ });
+
+ it('resolves a step exactly as the live sources would have', async () => {
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
+ findByIdAndProviderMock.mockResolvedValue({
+ abilities: { vision: true },
+ displayName: 'My GPT-4',
+ settings: { extendParams: ['reasoningEffort'] },
+ });
+ const ctx = createCtx();
+ const args = {
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ world: { agent: { chatConfig: {} } },
+ };
+
+ const live = await resolveServerCallLlmContextHints({ ...args, ctx });
+ // Non-trivial to compare against: the user's row and reasoning config both
+ // reached the payload.
+ expect(live.resolvedExtendParams).toMatchObject({ reasoning_effort: 'high' });
+ expect(live.modelDisplayName).toBe('My GPT-4');
+
+ // What discovery freezes onto the operation, read through the same server
+ // providers the live path used.
+ const modelFacts = await readFrozenModelFacts(
+ { agent: {}, model: 'gpt-4', provider: 'openai', topicId: ctx.topicId },
+ createServerModelParamsProviders({
+ builtinModels: await loadModelsMock(),
+ serverDB: ctx.serverDB,
+ userId: ctx.userId,
+ }),
+ );
+ const frozen = await resolveServerCallLlmContextHints({
+ ...args,
+ ctx: { ...ctx, modelRuntimeConfig: { modelFacts, model: 'gpt-4', provider: 'openai' } },
+ });
+
+ expect(frozen.resolvedExtendParams).toEqual(live.resolvedExtendParams);
+ expect(frozen.modelDisplayName).toBe(live.modelDisplayName);
+ expect(frozen.modelKnowledgeCutoff).toBe(live.modelKnowledgeCutoff);
+ expect(frozen.preserveThinkingForPayload).toBe(live.preserveThinkingForPayload);
+ expect(frozen.shouldReplayAssistantReasoning).toBe(live.shouldReplayAssistantReasoning);
+ expect(frozen.capabilities.isCanUseVision('gpt-4', 'openai')).toBe(
+ live.capabilities.isCanUseVision('gpt-4', 'openai'),
+ );
+ });
+
+ it('resolves live for an attempt on another model', async () => {
+ await resolveServerCallLlmContextHints({
+ ctx: frozenCtx(),
+ world: { agent: { chatConfig: {} } },
+ llmPayload,
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ });
+
+ expect(loadModelsMock).toHaveBeenCalled();
+ });
+
+ it('resolves live for an operation created before the snapshot existed', async () => {
+ await resolveServerCallLlmContextHints({
+ ctx: {
+ ...createCtx(),
+ modelRuntimeConfig: { model: 'gpt-4', provider: 'openai' },
+ },
+ world: { agent: { chatConfig: {} } },
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(loadModelsMock).toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
index 62b51d87c1f..1e1c6b39c9a 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
@@ -4,6 +4,7 @@ import {
stripAssistantReasoningForReplay,
} from '@lobechat/agent-runtime';
import {
+ createFrozenModelParamsProviders,
type ResolvedModelExtendParamList,
type ResolvedModelParams,
resolveModelExtendParamList,
@@ -95,8 +96,17 @@ export const resolveServerCallLlmContextHints = async ({
world,
}: ResolveServerCallLlmContextHintsInput): Promise<ServerCallLlmContextHints> => {
const agentConfig = world?.agent;
- const builtinModels = await loadModels();
const snapshot = ctx.modelRuntimeConfig;
+ // The run froze its model facts when the operation was created. Reuse them
+ // for the model they were read for: the bank, the user's model row and the
+ // reasoning config are then read zero times per step, and a card or effort
+ // the user edits mid-run cannot change the payload between two steps. An
+ // attempt on another model (a compression model), or an operation created
+ // before the snapshot existed, resolves live.
+ const frozenFacts =
+ snapshot?.modelFacts?.model === model && snapshot.modelFacts.provider === provider
+ ? snapshot.modelFacts
+ : undefined;
const resolved = await resolveModelParams(
{
@@ -108,20 +118,23 @@ export const resolveServerCallLlmContextHints = async ({
// 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
+ frozenFacts?.mediaCapabilities ??
+ (snapshot?.model === model && snapshot.provider === provider
? snapshot.mediaCapabilities
- : undefined,
+ : undefined),
model,
provider,
searchDecision: world?.searchDecision,
topicId: ctx.topicId,
},
- createServerModelParamsProviders({
- builtinModels,
- serverDB: ctx.serverDB,
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- }),
+ frozenFacts
+ ? createFrozenModelParamsProviders(frozenFacts)
+ : createServerModelParamsProviders({
+ builtinModels: await loadModels(),
+ serverDB: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ }),
);
const messages = llmPayload.messages as UIChatMessage[];
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
index fce50c60064..c38923ef822 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
@@ -360,11 +360,13 @@ describe('AI Agent Router Integration Tests', () => {
agentId: testAgentId,
}),
autoStart: false,
- modelRuntimeConfig: {
+ modelRuntimeConfig: expect.objectContaining({
mediaCapabilities: expect.objectContaining({ vision: true }),
+ // The run's model facts, read once during discovery.
+ modelFacts: expect.objectContaining({ model: 'gpt-4o-mini', provider: 'openai' }),
model: 'gpt-4o-mini',
provider: 'openai',
- },
+ }),
userId,
}),
);
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index acc148aafc0..bb6b097ae19 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -492,6 +492,37 @@ describe('AgentRuntimeService', () => {
});
});
+ it('keeps the frozen model facts on the run state but out of durable storage', async () => {
+ const recordStart = vi
+ .spyOn(AgentOperationModel.prototype, 'recordStart')
+ .mockResolvedValue(undefined);
+ const modelFacts = {
+ cards: [{ abilities: { vision: true }, id: 'gpt-4', providerId: 'openai' }],
+ model: 'gpt-4',
+ provider: 'openai',
+ };
+
+ await service.createOperation({
+ ...mockParams,
+ modelRuntimeConfig: { ...mockParams.modelRuntimeConfig, modelFacts },
+ });
+
+ // The steps read the snapshot back off the state.
+ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({
+ modelRuntimeConfig: expect.objectContaining({ modelFacts }),
+ }),
+ );
+ // The row that outlives the run, and the metadata copy, stay as small as
+ // they were: both only ever surface model / provider.
+ expect(recordStart.mock.calls[0][0].modelRuntimeConfig).toEqual({ model: 'gpt-4' });
+ expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ modelRuntimeConfig: { model: 'gpt-4' } }),
+ );
+ });
+
it('should create operation successfully with autoStart=false', async () => {
const params = { ...mockParams, autoStart: false };
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 78b26be1cc6..96dfd881edc 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -163,6 +163,21 @@ const DURABLE_LEASE_HEARTBEAT_EVERY_TICKS = 3;
const EVAL_TOOL_FORWARDING_HOOK_ID = 'eval-tool-forwarding';
const INTERVENTION_LIFECYCLE_CHECKPOINT_KEY = '_agentInterventionLifecycle';
+/**
+ * Drop the frozen model facts from a copy of `modelRuntimeConfig`.
+ *
+ * They exist so a live run's steps stop re-reading the model bank and the
+ * user's rows, and the run reads them back off its Redis state. The durable
+ * `agent_operations` row and the operation metadata only ever surface the model
+ * and provider, so neither needs to keep ~0.5KB of cards per operation β€” the row
+ * keeps them forever.
+ */
+const withoutFrozenModelFacts = (modelRuntimeConfig?: any) => {
+ if (!modelRuntimeConfig?.modelFacts) return modelRuntimeConfig;
+ const { modelFacts: _frozen, ...rest } = modelRuntimeConfig;
+ return rest;
+};
+
interface InterventionLifecycleCheckpoint {
state: 'completed' | 'pending';
stepIndex: number;
@@ -980,7 +995,7 @@ export class AgentRuntimeService {
}
: {}),
model: modelRuntimeConfig?.model,
- modelRuntimeConfig,
+ modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),
operationId,
parentOperationId: parentOperationId ?? null,
provider: modelRuntimeConfig?.provider,
@@ -1166,7 +1181,7 @@ export class AgentRuntimeService {
}
: undefined,
mirrorToOperationId,
- modelRuntimeConfig,
+ modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),
// Share-visitor runs execute as the creator (`userId`) but stream only
// to the visitor β€” the gateway registers the WS channel under this id.
streamOwnerUserId: agentShareVisitor?.visitorUserId,
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
index f81ac675d67..e44b8a96ac4 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
@@ -358,11 +358,16 @@ describe('AiAgentService.execAgent - model/provider override', () => {
const callArgs = mockCreateOperation.mock.calls[0][0];
expect(callArgs.agentConfig.model).toBe('step-3.7-flash');
expect(callArgs.agentConfig.provider).toBe('stepfun');
- expect(callArgs.modelRuntimeConfig).toEqual({
+ expect(callArgs.modelRuntimeConfig).toMatchObject({
mediaCapabilities: { video: true, vision: true },
model: 'step-3.7-flash',
provider: 'stepfun',
});
+ // The model facts frozen for the run follow the override too.
+ expect(callArgs.modelRuntimeConfig.modelFacts).toMatchObject({
+ model: 'step-3.7-flash',
+ provider: 'stepfun',
+ });
});
it('keeps the topic provider when only the model is overridden', async () => {
@@ -377,11 +382,16 @@ describe('AiAgentService.execAgent - model/provider override', () => {
});
const callArgs = mockCreateOperation.mock.calls[0][0];
- expect(callArgs.modelRuntimeConfig).toEqual({
+ expect(callArgs.modelRuntimeConfig).toMatchObject({
mediaCapabilities: { video: true, vision: true },
model: 'step-3.7-flash',
provider: 'stepfun',
});
+ // The model facts frozen for the run follow the override too.
+ expect(callArgs.modelRuntimeConfig.modelFacts).toMatchObject({
+ model: 'step-3.7-flash',
+ provider: 'stepfun',
+ });
});
it('uses the caller model preference when the workspace Agent allows member selection', async () => {
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index 53b1496990d..eace1cccaf8 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -274,6 +274,10 @@ export const startOperation = async (
...(typeof video === 'boolean' && { video }),
...(typeof vision === 'boolean' && { vision }),
},
+ // Read once during discovery: every LLM attempt of this run resolves its
+ // parameters from here, so no step re-reads the bank, the user's model
+ // row or the reasoning config β€” and none of them can change mid-run.
+ modelFacts: discovery.modelFacts,
model,
provider,
},
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index 8222e27a387..8bbeaff5138 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -18,11 +18,12 @@ import type {
import type { LobeChatDatabase } from '@lobechat/database';
import type { DeviceUnavailableErrorData } from '@lobechat/device-gateway-client';
import {
+ readFrozenModelFacts,
resolveClientExecutors,
resolveDiscoveryPool,
resolveInvocationToolIds,
} from '@lobechat/mecha';
-import type { ChatTopicBotContext, RequestTrigger } from '@lobechat/types';
+import type { ChatTopicBotContext, FrozenModelFacts, RequestTrigger } from '@lobechat/types';
import {
agentShareFileAccessScope,
getActivePluginIds,
@@ -55,6 +56,7 @@ import { resolveModelMediaCapabilities } from '@/server/modules/AgentRuntime/res
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import type { ServerAgentToolsContext } from '@/server/modules/Mecha';
import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
+import { createServerModelParamsProviders } from '@/server/modules/Mecha/ModelParams/providers';
import type { AgentDocumentsService } from '@/server/services/agentDocuments';
import {
isAgentSignalEnabledForUser,
@@ -146,6 +148,8 @@ export interface ToolDiscoveryResult {
hasAgentDocuments: boolean;
hasEnabledKnowledgeBases: boolean;
lobehubSkillManifests: LobeToolManifest[];
+ /** Model facts read once for the whole operation; see {@link FrozenModelFacts}. */
+ modelFacts: FrozenModelFacts;
modelMediaCapabilities: Pick<ModelAbilities, 'audio' | 'video' | 'vision'>;
onlineDevices: DeviceAttachment[];
operationAgentGroup?: AgentGroupConfig;
@@ -318,6 +322,35 @@ export const discoverTools = async (
provider,
userAbilities: activeModelAbilities,
}) ?? {};
+ // The rest of the run's model facts, read here because this stage already
+ // holds the loaded bank and the user's model row. Everything downstream β€” one
+ // per step, retries included β€” reads them back off the operation instead.
+ const modelFacts = await readFrozenModelFacts(
+ {
+ agent: { id: agentConfig.id },
+ mediaCapabilities: modelMediaCapabilities,
+ model,
+ provider,
+ topicId,
+ },
+ {
+ ...createServerModelParamsProviders({
+ builtinModels,
+ serverDB: deps.db,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ }),
+ // Reuse the row read above rather than querying it a second time.
+ getUserModelRow: async () =>
+ activeModelMetadata
+ ? {
+ abilities: activeModelMetadata.abilities,
+ displayName: activeModelMetadata.displayName,
+ extendParams: activeModelMetadata.settings?.extendParams ?? undefined,
+ }
+ : null,
+ },
+ );
const searchDecision = resolveServerSearchDecision({
builtinModels,
chatConfig: agentConfig.chatConfig ?? undefined,
@@ -1097,6 +1130,7 @@ export const discoverTools = async (
hasAgentDocuments,
hasEnabledKnowledgeBases,
lobehubSkillManifests,
+ modelFacts,
modelMediaCapabilities,
onlineDevices,
operationAgentGroup,
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 79936983036..4e724722ef4 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -20,6 +20,7 @@ import type {
EvalToolForwardingConfig,
ExecutionPlan,
ExpertiseContextSnapshot,
+ FrozenModelFacts,
LobeAgentChatConfig,
LobeAgentConfig,
SecurityBlacklistConfig,
@@ -350,6 +351,15 @@ export interface AgentState {
video?: boolean;
vision?: boolean;
};
+ /**
+ * Every model fact the host read once when the operation was created (cards,
+ * the user's model row, the reasoning config that won the topic pin). Every
+ * LLM attempt of the run resolves its parameters from this snapshot, so an
+ * edit the user makes mid-run lands on the next turn instead of changing the
+ * payload between two steps. Absent on operations created before it existed,
+ * and for an attempt on another model β€” those resolve live.
+ */
+ modelFacts?: FrozenModelFacts;
model: string;
provider: string;
/**
diff --git a/packages/mecha/src/modelParams/index.ts b/packages/mecha/src/modelParams/index.ts
index 92a2c7995ed..d22eeb6b4f6 100644
--- a/packages/mecha/src/modelParams/index.ts
+++ b/packages/mecha/src/modelParams/index.ts
@@ -1,4 +1,6 @@
export {
+ createFrozenModelParamsProviders,
+ readFrozenModelFacts,
resolveHistoryCount,
resolveModelExtendParamList,
resolveModelParams,
diff --git a/packages/mecha/src/modelParams/resolveModelParams.test.ts b/packages/mecha/src/modelParams/resolveModelParams.test.ts
index 1aad55e7703..d1197a8b743 100644
--- a/packages/mecha/src/modelParams/resolveModelParams.test.ts
+++ b/packages/mecha/src/modelParams/resolveModelParams.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from 'vitest';
-import { resolveHistoryCount, resolveModelParams } from './resolveModelParams';
+import {
+ createFrozenModelParamsProviders,
+ readFrozenModelFacts,
+ resolveHistoryCount,
+ resolveModelParams,
+} from './resolveModelParams';
import type { ModelCardFacts, ModelParamsProviders, ModelParamsRequest } from './types';
const cards: ModelCardFacts[] = [
@@ -312,3 +317,97 @@ describe('resolveHistoryCount', () => {
expect(resolveHistoryCount(null)).toBeUndefined();
});
});
+
+describe('frozen model facts', () => {
+ const liveProviders = () => ({
+ findTopicReasoningPin: vi.fn<NonNullable<ModelParamsProviders['findTopicReasoningPin']>>(
+ async () => ({
+ model: 'gpt-4',
+ provider: 'openai',
+ reasoningConfig: { reasoningEffort: 'low' },
+ }),
+ ),
+ getModelReasoningConfig: vi.fn<NonNullable<ModelParamsProviders['getModelReasoningConfig']>>(
+ async () => ({ reasoningEffort: 'high' }),
+ ),
+ getUserModelRow: vi.fn<NonNullable<ModelParamsProviders['getUserModelRow']>>(async () => ({
+ displayName: 'My GPT-4',
+ })),
+ listModelCards: vi.fn(() => cards),
+ });
+
+ it('resolves the same params off the snapshot without reading a single source again', async () => {
+ const live = liveProviders();
+ const expected = await resolveModelParams(request(), live);
+
+ const facts = await readFrozenModelFacts(request(), live);
+ const reads = liveProviders();
+ // The live sources are laid underneath on purpose: the snapshot must answer
+ // everything, so none of them may be touched.
+ const fromSnapshot = await resolveModelParams(request(), {
+ ...reads,
+ ...createFrozenModelParamsProviders(facts),
+ });
+
+ expect(fromSnapshot.modelDisplayName).toBe(expected.modelDisplayName);
+ expect(fromSnapshot.modelKnowledgeCutoff).toBe(expected.modelKnowledgeCutoff);
+ expect(fromSnapshot.modelExtendParams).toEqual(expected.modelExtendParams);
+ expect(fromSnapshot.resolvedExtendParams).toEqual(expected.resolvedExtendParams);
+ expect(fromSnapshot.capabilities.isCanUseFC('gpt-4', 'openai')).toBe(true);
+ expect(fromSnapshot.capabilities.isCanUseVision('gpt-4', 'openai')).toBe(true);
+ expect(reads.findTopicReasoningPin).not.toHaveBeenCalled();
+ expect(reads.getModelReasoningConfig).not.toHaveBeenCalled();
+ expect(reads.getUserModelRow).not.toHaveBeenCalled();
+ expect(reads.listModelCards).not.toHaveBeenCalled();
+ });
+
+ it('survives the state round-trip as plain JSON', async () => {
+ const facts = await readFrozenModelFacts(request(), liveProviders());
+ // Deliberately JSON, not structuredClone: the state is stored as JSON.
+ // eslint-disable-next-line unicorn/prefer-structured-clone
+ expect(JSON.parse(JSON.stringify(facts))).toEqual(facts);
+ // Only the two cards the rules can match, never the whole bank.
+ expect(facts.cards.map((card) => `${card.providerId}/${card.id}`)).toEqual([
+ 'openai/gpt-4',
+ 'lobehub/gpt-4',
+ ]);
+ });
+
+ it('keeps the effort the run started with when the user edits it mid-run', async () => {
+ const live = liveProviders();
+ const facts = await readFrozenModelFacts(request(), live);
+ expect(facts.reasoningConfig).toEqual({ reasoningEffort: 'low' });
+
+ // The user re-pins the topic and changes the model-instance config: the
+ // running operation must keep answering with what it froze.
+ live.findTopicReasoningPin.mockResolvedValue({
+ model: 'gpt-4',
+ provider: 'openai',
+ reasoningConfig: { reasoningEffort: 'high' },
+ });
+ const later = await resolveModelParams(request(), createFrozenModelParamsProviders(facts));
+ expect(later.resolvedExtendParams).toMatchObject({ reasoning_effort: 'low' });
+ });
+
+ it('freezes no reasoning source for a model that cannot consume one', async () => {
+ const live = liveProviders();
+ const facts = await readFrozenModelFacts(request({ model: 'plain' }), live);
+ expect(facts.reasoningConfig).toBeUndefined();
+ expect(live.findTopicReasoningPin).not.toHaveBeenCalled();
+ expect(live.getModelReasoningConfig).not.toHaveBeenCalled();
+ });
+
+ it('answers for the frozen model only, so another model cannot inherit its row', async () => {
+ const facts = await readFrozenModelFacts(request(), liveProviders());
+ const other = await resolveModelParams(
+ request({ model: 'plain' }),
+ createFrozenModelParamsProviders(facts),
+ );
+ expect(other.userModelRow).toBeUndefined();
+ expect(other.modelDisplayName).toBeUndefined();
+ // No card for the compression model in the snapshot: function calling is
+ // assumed and no native media is claimed, as for any unknown card.
+ expect(other.capabilities.isCanUseFC('plain', 'openai')).toBe(true);
+ expect(other.capabilities.isCanUseVision('plain', 'openai')).toBe(false);
+ });
+});
diff --git a/packages/mecha/src/modelParams/resolveModelParams.ts b/packages/mecha/src/modelParams/resolveModelParams.ts
index af1ab3f1936..f3067bda215 100644
--- a/packages/mecha/src/modelParams/resolveModelParams.ts
+++ b/packages/mecha/src/modelParams/resolveModelParams.ts
@@ -18,6 +18,7 @@ import {
import { ModelProvider } from 'model-bank/modelProvider';
import type {
+ FrozenModelFacts,
MediaCapabilities,
ModelCardFacts,
ModelParamsProviders,
@@ -125,6 +126,74 @@ const resolveReasoningConfig = async (
);
};
+/**
+ * Read every model fact of one run once, as plain data the host can freeze onto
+ * the operation. Each later LLM attempt then resolves its parameters from that
+ * snapshot via {@link createFrozenModelParamsProviders}, so a run sees one model
+ * from its first step to its last: a card the user edits, a model row they
+ * change or an effort they pick mid-run applies to the next turn, not to this
+ * one, and no step pays for the lookups again.
+ */
+export const readFrozenModelFacts = async (
+ request: ModelParamsRequest,
+ providers: ModelParamsProviders,
+): Promise<FrozenModelFacts> => {
+ const { model, provider } = request;
+ const { canonicalModelCard, modelCard, modelHasReasoningExtendParams, userModelRow } =
+ await resolveModelExtendParamList(request, providers);
+ // Read the reasoning sources only for models that can consume them, exactly
+ // as the per-attempt rules do: a non-reasoning model freezes none.
+ const reasoningConfig = modelHasReasoningExtendParams
+ ? await resolveReasoningConfig(request, providers)
+ : undefined;
+
+ return {
+ // Only the two cards the rules can match β€” the provider's own and the
+ // canonical one of the same id elsewhere. The whole bank would not fit the
+ // state, and nothing asks about another model (see the frozen providers).
+ cards: [modelCard, canonicalModelCard].filter(
+ (card, index, all): card is ModelCardFacts => !!card && all.indexOf(card) === index,
+ ),
+ // Only the three flags the rules read: a host may hand over a fuller
+ // abilities object, and the state pays for every key it keeps.
+ mediaCapabilities: request.mediaCapabilities && {
+ audio: request.mediaCapabilities.audio,
+ video: request.mediaCapabilities.video,
+ vision: request.mediaCapabilities.vision,
+ },
+ model,
+ provider,
+ reasoningConfig,
+ userModelRow,
+ };
+};
+
+/**
+ * Answer the rules from a frozen snapshot: no model bank, no database, no topic
+ * read. The topic-pin precedence was already applied when the facts were read,
+ * so the pin provider stays absent and the frozen config answers directly.
+ *
+ * Only the frozen model is answered for. A capability question about any other
+ * model (a compression model reusing this context) falls back to the rules' own
+ * "no card" defaults, and a run whose attempt model differs should resolve live
+ * instead of freezing the wrong row onto it.
+ */
+export const createFrozenModelParamsProviders = (facts: FrozenModelFacts): ModelParamsProviders => {
+ const isFrozenModel = (model: string, provider: string) =>
+ model === facts.model && provider === facts.provider;
+
+ return {
+ // Explicitly absent, so overlaying these onto a host's live providers cannot
+ // reintroduce the topic read the snapshot already resolved.
+ findTopicReasoningPin: undefined,
+ getModelReasoningConfig: async (model, provider) =>
+ isFrozenModel(model, provider) ? facts.reasoningConfig : undefined,
+ getUserModelRow: async (model, provider) =>
+ isFrozenModel(model, provider) ? facts.userModelRow : undefined,
+ listModelCards: () => facts.cards,
+ };
+};
+
const isNonEmptyRecord = (value: unknown): value is Record<string, unknown> =>
!!value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
diff --git a/packages/mecha/src/modelParams/types.ts b/packages/mecha/src/modelParams/types.ts
index 0dc9df40689..c5a254107e8 100644
--- a/packages/mecha/src/modelParams/types.ts
+++ b/packages/mecha/src/modelParams/types.ts
@@ -1,27 +1,16 @@
import type { ModelExtendParams } from '@lobechat/model-runtime/utils/modelExtendParams';
-import type { LobeAgentChatConfig } from '@lobechat/types';
-import type { AiModelReasoningConfig, ModelAbilities } from 'model-bank';
+import type {
+ FrozenModelFacts,
+ LobeAgentChatConfig,
+ ModelCardFacts,
+ ModelMediaCapabilities,
+ UserModelRowFacts,
+} from '@lobechat/types';
+import type { AiModelReasoningConfig } 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 facts a host reads for the rules are also what an operation freezes onto
+// its state, so they are declared once in `@lobechat/types`.
+export type { FrozenModelFacts, ModelCardFacts, UserModelRowFacts };
/** The reasoning config a topic pinned at creation, with the model it was pinned for. */
export interface TopicReasoningPinFacts {
@@ -32,7 +21,7 @@ export interface TopicReasoningPinFacts {
reasoningConfig?: AiModelReasoningConfig | null;
}
-export type MediaCapabilities = Pick<ModelAbilities, 'audio' | 'video' | 'vision'>;
+export type MediaCapabilities = ModelMediaCapabilities;
/** Everything the model-parameter rules read about the run. */
export interface ModelParamsRequest {
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 7f5ba73efa5..05c5dbc4998 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -4,6 +4,8 @@ import type { DeviceUnavailableErrorData, WorkingDirConfig } from '../device';
import type { TaskDetail, UIChatMessage } from '../message';
import type { ChatTopic } from '../topic';
+export * from './modelFacts';
+
export type AgentSignalOperationKind =
'memory' | 'nightly-review' | 'self-feedback-intent' | 'self-reflection' | 'skill';
diff --git a/packages/types/src/agentExecution/modelFacts.ts b/packages/types/src/agentExecution/modelFacts.ts
new file mode 100644
index 00000000000..a91aa1ecd1e
--- /dev/null
+++ b/packages/types/src/agentExecution/modelFacts.ts
@@ -0,0 +1,47 @@
+import type { AiModelReasoningConfig, ModelAbilities } from 'model-bank';
+
+/** The subset of a model card the model-parameter 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;
+}
+
+/** What a model can take natively, as the run decided it. */
+export type ModelMediaCapabilities = Pick<ModelAbilities, 'audio' | 'video' | 'vision'>;
+
+/**
+ * Every model fact an operation read once when it was created: the cards the
+ * rules match against, the user's own model row, the media capabilities and the
+ * reasoning config that won the topic-pin β†’ user-config precedence.
+ *
+ * Carried on `AgentState.modelRuntimeConfig` (plain JSON, like the rest of the
+ * state) so all of a run's LLM attempts β€” first step, last step and every retry
+ * in between β€” resolve their parameters from one snapshot. A model or effort the
+ * user edits mid-run belongs to the next turn, not to this one.
+ */
+export interface FrozenModelFacts {
+ /** The provider's card for `model` plus, when it exists, the canonical card of the same id under another provider. */
+ cards: ModelCardFacts[];
+ mediaCapabilities?: ModelMediaCapabilities;
+ /** The model the facts were read for; a mismatch (e.g. a compression model) means resolve live. */
+ model: string;
+ provider: string;
+ /** Absent when the model cannot consume reasoning params at all. */
+ reasoningConfig?: AiModelReasoningConfig;
+ userModelRow?: UserModelRowFacts;
+}