🤯 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
✨ feat(heterogeneous-agent): support relay models in Codex (#18609)
AmAzing-06b6447df584
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.tsindex 7e97c0c56d1..5c13a6290e4 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts@@ -1,3 +1,5 @@+import path from 'node:path';+import { describe, expect, it } from 'vitest';import type { PrepareProviderBindingContext } from '../types';@@ -41,10 +43,53 @@ describe('codexDriver provider binding', () => {expect(config).toContain('model = "lobehub/gpt-5.4"');expect(config).toContain('base_url = "https://app.example.com/api/v1/openai/v1"');expect(config).toContain('env_key = "LOBEHUB_HETERO_TOKEN"');+ expect(config).not.toContain('model_catalog_json');+ expect(plan.profileFiles).toHaveLength(1);expect(config).not.toContain('stale');expect(plan.env.LOBEHUB_HETERO_TOKEN).toBeUndefined();});+ it.each([+ ['deepseek-v4-flash', 'high', ['low', 'high', 'max'], 'tokens'],+ ['deepseek-v4-pro', 'high', ['low', 'high', 'max'], 'tokens'],+ ['glm-5.2', 'max', ['high', 'max'], 'bytes'],+ ] as const)(+ 'writes a current Codex model catalog for %s',+ async (selectedModel, defaultReasoningLevel, reasoningLevels, truncationMode) => {+ const profileDir = 'C:\\managed\\codex';+ const plan = await codexDriver.prepareServerDefaultBinding!({+ args: [],+ endpoint: 'https://app.example.com',+ env: {},+ model: selectedModel,+ profileDir,+ });+ const config = plan.profileFiles?.find(({ path }) => path === 'config.toml')?.content ?? '';+ const catalogContent = plan.profileFiles?.find(({ path }) => path === 'models.json')?.content;+ const catalog = JSON.parse(catalogContent ?? '{}');+ const model = catalog.models?.[0];++ expect(plan.args).toEqual(['--model', `lobehub/${selectedModel}`]);+ expect(config).toContain(+ `model_catalog_json = ${JSON.stringify(path.join(profileDir, 'models.json'))}`,+ );+ expect(catalog.models).toHaveLength(1);+ expect(model).toMatchObject({+ apply_patch_tool_type: null,+ context_window: 1_048_576,+ default_reasoning_level: defaultReasoningLevel,+ max_context_window: 1_048_576,+ shell_type: 'unified_exec',+ slug: `lobehub/${selectedModel}`,+ supports_reasoning_summary_parameter: false,+ truncation_policy: { limit: 10_000, mode: truncationMode },+ });+ expect(+ model.supported_reasoning_levels.map(({ effort }: { effort: string }) => effort),+ ).toEqual(reasoningLevels);+ },+ );+it('writes a secret-free Responses provider config and injects the key through env', async () => {const plan = await codexDriver.prepareProviderBinding!(bindingContext());const config = plan.profileFiles?.[0]?.content ?? '';diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.tsindex f2554cd42c4..bd5d4ae6f24 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts@@ -1,9 +1,16 @@+import path from 'node:path';+import {CODEX_DEFAULT_EXECUTION_ARGS,CODEX_EXECUTION_MODE_FLAGS,CODEX_REQUIRED_ARGS,} from '@lobechat/heterogeneous-agents/spawn';-import { formatServerDefaultHeterogeneousModel } from '@lobechat/types';+import type { CodexReasoningEffort, CodexServerDefaultCustomModel } from '@lobechat/types';+import {+ formatServerDefaultHeterogeneousModel,+ getCodexReasoningEffortLevels,+ isCodexServerDefaultCustomModel,+} from '@lobechat/types';import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';@@ -13,10 +20,57 @@ const hasAnyFlag = (args: string[], flags: readonly string[]) =>const HOST_PROVIDER_ID = 'lobehub';const HOST_API_KEY_ENV = 'LOBEHUB_CODEX_API_KEY';const SERVER_TOKEN_ENV = 'LOBEHUB_HETERO_TOKEN';+const SERVER_DEFAULT_MODEL_CATALOG_FILE = 'models.json';++interface CodexServerDefaultModelMetadata {+ contextWindow: number;+ defaultReasoningLevel: CodexReasoningEffort;+ description: string;+ displayName: string;+ truncationMode: 'bytes' | 'tokens';+}++const CODEX_SERVER_DEFAULT_MODEL_METADATA = {+ 'deepseek-v4-flash': {+ contextWindow: 1_048_576,+ defaultReasoningLevel: 'high',+ description: 'Fast, cost-efficient DeepSeek V4 model for agentic coding.',+ displayName: 'DeepSeek V4 Flash',+ truncationMode: 'tokens',+ },+ 'deepseek-v4-pro': {+ contextWindow: 1_048_576,+ defaultReasoningLevel: 'high',+ description: 'DeepSeek V4 flagship model for complex agentic coding tasks.',+ displayName: 'DeepSeek V4 Pro',+ truncationMode: 'tokens',+ },+ 'glm-5.2': {+ contextWindow: 1_048_576,+ defaultReasoningLevel: 'max',+ description: 'GLM-5.2 flagship model for long-horizon engineering tasks.',+ displayName: 'GLM-5.2',+ truncationMode: 'bytes',+ },+} as const satisfies Record<CodexServerDefaultCustomModel, CodexServerDefaultModelMetadata>;++const CODEX_REASONING_LEVEL_DESCRIPTIONS = {+ high: 'Enhanced reasoning for complex tasks',+ low: 'Fast responses with lighter reasoning',+ max: 'Maximum reasoning depth for the hardest tasks',+} as const satisfies Partial<Record<CodexReasoningEffort, string>>;++const CODEX_SERVER_DEFAULT_BASE_INSTRUCTIONS =+ 'You are Codex, a coding agent working with the user in a shared workspace. Follow the provided instructions, use tools when helpful, verify your changes, and report results clearly.';const isConflictingConfigOverride = (value: string): boolean => {const key = value.split('=', 1)[0]?.trim();- return key === 'model' || key === 'model_provider' || key.startsWith('model_providers.');+ return (+ key === 'model' ||+ key === 'model_catalog_json' ||+ key === 'model_provider' ||+ key.startsWith('model_providers.')+ );};export const sanitizeCodexProviderBindingArgs = (source: string[]): string[] => {@@ -57,6 +111,53 @@ const sanitizeCodexProviderBindingEnv = (source: Record<string, string> | undeficonst tomlString = (value: string): string => JSON.stringify(value);+const buildServerDefaultModelCatalog = (+ model: CodexServerDefaultCustomModel,+ requestModel: string,+) => {+ const metadata = CODEX_SERVER_DEFAULT_MODEL_METADATA[model];+ const supportedReasoningLevels = getCodexReasoningEffortLevels(model).map((effort) => ({+ description: CODEX_REASONING_LEVEL_DESCRIPTIONS[effort] ?? `${effort} reasoning`,+ effort,+ }));++ return `${JSON.stringify(+ {+ models: [+ {+ // The relay bridge currently carries function tools. Keep patch editing+ // on the unified exec path instead of advertising a dropped custom tool.+ apply_patch_tool_type: null,+ availability_nux: null,+ base_instructions: CODEX_SERVER_DEFAULT_BASE_INSTRUCTIONS,+ context_window: metadata.contextWindow,+ default_reasoning_level: metadata.defaultReasoningLevel,+ default_reasoning_summary: 'none',+ default_verbosity: null,+ description: metadata.description,+ display_name: metadata.displayName,+ effective_context_window_percent: 95,+ experimental_supported_tools: [],+ input_modalities: ['text'],+ max_context_window: metadata.contextWindow,+ priority: 0,+ shell_type: 'unified_exec',+ slug: requestModel,+ support_verbosity: false,+ supported_in_api: true,+ supported_reasoning_levels: supportedReasoningLevels,+ supports_reasoning_summary_parameter: false,+ truncation_policy: { limit: 10_000, mode: metadata.truncationMode },+ upgrade: null,+ visibility: 'list',+ },+ ],+ },+ null,+ 2,+ )}\n`;+};+const buildCodexOptionArgs = async ({args,helpers,@@ -125,9 +226,14 @@ export const codexDriver: HeterogeneousAgentDriver = {},prepareServerDefaultBinding({ args, endpoint, env, model, profileDir }) {const requestModel = formatServerDefaultHeterogeneousModel(model);+ const customModel = isCodexServerDefaultCustomModel(model) ? model : undefined;+ const modelCatalogPath = customModel+ ? path.join(profileDir, SERVER_DEFAULT_MODEL_CATALOG_FILE)+ : undefined;const config = [`model = ${tomlString(requestModel)}`,`model_provider = ${tomlString(HOST_PROVIDER_ID)}`,+ ...(modelCatalogPath ? [`model_catalog_json = ${tomlString(modelCatalogPath)}`] : []),'',`[model_providers.${HOST_PROVIDER_ID}]`,`name = ${tomlString('LobeHub Server Default')}`,@@ -141,7 +247,17 @@ export const codexDriver: HeterogeneousAgentDriver = {return {args: [...sanitizeCodexProviderBindingArgs(args), '--model', requestModel],env: { ...sanitizeCodexProviderBindingEnv(env), CODEX_HOME: profileDir },- profileFiles: [{ content: config, path: 'config.toml' }],+ profileFiles: [+ { content: config, path: 'config.toml' },+ ...(customModel+ ? [+ {+ content: buildServerDefaultModelCatalog(customModel, requestModel),+ path: SERVER_DEFAULT_MODEL_CATALOG_FILE,+ },+ ]+ : []),+ ],};},};diff --git a/apps/server/src/modules/ModelRuntime/index.test.ts b/apps/server/src/modules/ModelRuntime/index.test.tsindex c99242cf233..27b45599000 100644--- a/apps/server/src/modules/ModelRuntime/index.test.ts+++ b/apps/server/src/modules/ModelRuntime/index.test.ts@@ -205,13 +205,31 @@ describe('getServerDefaultHeterogeneousModels', () => {});});- it('offers every tool-capable relay model to Claude Code without widening Codex', async () => {+ it('offers tool-capable relay models to Claude Code and only explicit custom models to Codex', async () => {getServerGlobalConfig.mockResolvedValue({aiProvider: {lobehub: {enabled: true,serverModelLists: [{ abilities: { functionCall: true }, enabled: true, id: 'kimi-k2.6', type: 'chat' },+ {+ abilities: { functionCall: true },+ enabled: true,+ id: 'deepseek-v4-flash',+ type: 'chat',+ },+ {+ abilities: { functionCall: true },+ enabled: true,+ id: 'deepseek-v4-pro',+ type: 'chat',+ },+ {+ abilities: { functionCall: true },+ enabled: true,+ id: 'glm-5.2',+ type: 'chat',+ },{abilities: { functionCall: true },enabled: true,@@ -227,8 +245,14 @@ describe('getServerDefaultHeterogeneousModels', () => {});await expect(getServerDefaultHeterogeneousModels()).resolves.toEqual({- 'claude-code': [{ model: 'kimi-k2.6' }, { model: 'gemini-3.1-pro-preview' }],- 'codex': [],+ 'claude-code': [+ { model: 'kimi-k2.6' },+ { model: 'deepseek-v4-flash' },+ { model: 'deepseek-v4-pro' },+ { model: 'glm-5.2' },+ { model: 'gemini-3.1-pro-preview' },+ ],+ 'codex': [{ model: 'deepseek-v4-flash' }, { model: 'deepseek-v4-pro' }, { model: 'glm-5.2' }],});});diff --git a/apps/server/src/modules/ModelRuntime/index.ts b/apps/server/src/modules/ModelRuntime/index.tsindex 7ee9335de2f..08b8c5dcb59 100644--- a/apps/server/src/modules/ModelRuntime/index.ts+++ b/apps/server/src/modules/ModelRuntime/index.ts@@ -21,6 +21,7 @@ import {type SuperGrokKeyVault,type VertexAIKeyVault,} from '@lobechat/types';+import { isCodexServerDefaultCustomModel } from '@lobechat/types';import { safeParseJSON } from '@lobechat/utils';import { type AiFullModelCard, ModelProvider } from 'model-bank';import { AiProviderBaseURLSchema } from 'model-bank/aiProvider';@@ -548,9 +549,10 @@ export type ServerDefaultHeterogeneousModels = Record<* `parseClaudeModelId` arm keeps Claude ids eligible in deployments whose* catalog omits `abilities`.*- * Codex stays pinned to models that natively speak OpenAI Responses: the CLI- * branches its own reasoning/continuation behaviour on the model id, so a- * namespaced third-party id lands in an unverified default path.+ * Codex accepts native Responses models plus an explicit set of tool-capable+ * relay models configured through its custom model-catalog path. Keep that set+ * narrow: the CLI branches reasoning and continuation behaviour on model+ * metadata, so function calling alone is not enough to establish compatibility.*/const supportsServerDefaultHeterogeneousAgent = (agentType: ServerDefaultHeterogeneousAgentType,@@ -558,7 +560,8 @@ const supportsServerDefaultHeterogeneousAgent = () =>agentType === 'claude-code'? parseClaudeModelId(model.id) !== undefined || model.abilities?.functionCall === true- : isResponsesAPIModel(model.id);+ : isResponsesAPIModel(model.id) ||+ (isCodexServerDefaultCustomModel(model.id) && model.abilities?.functionCall === true);const getEnabledServerChatModels = async (provider: ModelProvider) => {const providerConfig = (await getServerGlobalConfig()).aiProvider[provider];diff --git a/packages/openapi/src/services/heterogeneous-direct.service.test.ts b/packages/openapi/src/services/heterogeneous-direct.service.test.tsindex cf3674c7662..dd807a4fab7 100644--- a/packages/openapi/src/services/heterogeneous-direct.service.test.ts+++ b/packages/openapi/src/services/heterogeneous-direct.service.test.ts@@ -99,17 +99,64 @@ describe('heterogeneous direct invocation protocol', () => {const result = await invokeServerDefaultModel({agentType: 'codex',model: 'gpt-5.4',- payload: { messages: [], model: 'lobehub-default', stream: true },+ payload: {+ apiMode: 'responses',+ messages: [],+ model: 'lobehub-default',+ reasoning: { effort: 'high', summary: 'detailed' },+ stream: true,+ },signal: new AbortController().signal,userId: 'user-1',});const runtimePayload = chat.mock.calls[0][0];expect(result.model).toBe('prod-gpt');- expect(runtimePayload).toMatchObject({ messages: [], model: 'prod-gpt', stream: true });+ expect(runtimePayload).toMatchObject({+ apiMode: 'responses',+ messages: [],+ model: 'prod-gpt',+ reasoning: { effort: 'high', summary: 'detailed' },+ stream: true,+ });expect(runtimePayload).not.toHaveProperty('deploymentName');});+ it('adapts custom Codex relay models to chat completions with their reasoning effort', async () => {+ const chat = vi.fn().mockResolvedValue(new Response('stream'));+ vi.mocked(resolveServerDefaultHeterogeneousModel).mockResolvedValue({+ model: 'deepseek-v4-pro',+ provider: 'lobehub',+ });+ vi.mocked(initModelRuntimeFromServerConfig).mockResolvedValue({+ chat,+ } as unknown as Awaited<ReturnType<typeof initModelRuntimeFromServerConfig>>);++ await invokeServerDefaultModel({+ agentType: 'codex',+ model: 'deepseek-v4-pro',+ payload: {+ apiMode: 'responses',+ messages: [],+ model: 'lobehub-default',+ reasoning: { effort: 'max', summary: 'detailed' },+ stream: true,+ },+ signal: new AbortController().signal,+ userId: 'user-1',+ });++ const runtimePayload = chat.mock.calls[0][0];+ expect(runtimePayload).toMatchObject({+ apiMode: 'chatCompletion',+ messages: [],+ model: 'deepseek-v4-pro',+ reasoning_effort: 'max',+ stream: true,+ });+ expect(runtimePayload).not.toHaveProperty('reasoning');+ });+it('fails closed before runtime initialization for an unsupported direct protocol route', async () => {vi.mocked(resolveServerDefaultHeterogeneousModel).mockRejectedValue(new Error('unsupported agent/runtime pair'),diff --git a/packages/openapi/src/services/heterogeneous-direct.service.ts b/packages/openapi/src/services/heterogeneous-direct.service.tsindex 4a790511650..712984b27ac 100644--- a/packages/openapi/src/services/heterogeneous-direct.service.ts+++ b/packages/openapi/src/services/heterogeneous-direct.service.ts@@ -5,7 +5,12 @@ import type {OpenAIChatMessage,UserMessageContentPart,} from '@lobechat/model-runtime';-import { RequestTrigger } from '@lobechat/types';+import type { CodexReasoningEffort } from '@lobechat/types';+import {+ getCodexReasoningEffortLevels,+ isCodexServerDefaultCustomModel,+ RequestTrigger,+} from '@lobechat/types';import { isRecord } from '@lobechat/utils/object';import type { ServerDefaultHeterogeneousAgentType } from '@/server/modules/ModelRuntime';@@ -829,9 +834,24 @@ export const invokeServerDefaultModel = async (params: {actorUserId: params.userId,workspaceId: params.workspaceId,});+ const { reasoning, ...chatCompletionsPayload } = params.payload;+ const requestedReasoningEffort = reasoning?.effort;+ const reasoningEffort = getCodexReasoningEffortLevels(params.model).includes(+ requestedReasoningEffort as CodexReasoningEffort,+ )+ ? (requestedReasoningEffort as ChatStreamPayload['reasoning_effort'])+ : undefined;+ const payload =+ params.agentType === 'codex' && isCodexServerDefaultCustomModel(params.model)+ ? {+ ...chatCompletionsPayload,+ apiMode: 'chatCompletion' as const,+ reasoning_effort: params.payload.reasoning_effort ?? reasoningEffort,+ }+ : params.payload;const response = await runtime.chat({- ...params.payload,+ ...payload,model,stream: true,},diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.tsindex adf4f832a60..e56a22ade5e 100644--- a/packages/types/src/agent/agencyConfig.test.ts+++ b/packages/types/src/agent/agencyConfig.test.ts@@ -610,6 +610,12 @@ describe('codex reasoning effort capabilities', () => {expect(getCodexReasoningEffortLevels('gpt-5.6-luna')).toEqual(maxLevels);});+ it('uses the model-specific levels supported by custom server-default models', () => {+ expect(getCodexReasoningEffortLevels('deepseek-v4-flash')).toEqual(['low', 'high', 'max']);+ expect(getCodexReasoningEffortLevels('deepseek-v4-pro')).toEqual(['low', 'high', 'max']);+ expect(getCodexReasoningEffortLevels('glm-5.2')).toEqual(['high', 'max']);+ });+it('uses conservative common levels for old, unknown, and default models', () => {expect(getCodexReasoningEffortLevels('gpt-5.5')).toEqual(commonLevels);expect(getCodexReasoningEffortLevels('gpt-5.4-mini')).toEqual(commonLevels);diff --git a/packages/types/src/agent/heteroSelectorCapabilities.test.ts b/packages/types/src/agent/heteroSelectorCapabilities.test.tsindex 75e1fc3de2b..ea7daeb9874 100644--- a/packages/types/src/agent/heteroSelectorCapabilities.test.ts+++ b/packages/types/src/agent/heteroSelectorCapabilities.test.ts@@ -4,8 +4,10 @@ import type { HeterogeneousProviderConfig } from './agencyConfig';import { buildHeteroSpawnArgs } from './agencyConfig';import {applyHeteroSelection,+ CODEX_SERVER_DEFAULT_CUSTOM_MODELS,getHeteroSelectorCapability,HETEROGENEOUS_AGENT_DEFAULT_SELECTION,+ isCodexServerDefaultCustomModel,isHeteroSelectorAvailable,} from './heteroSelectorCapabilities';@@ -53,6 +55,16 @@ describe('selector availability', () => {expect(getHeteroSelectorCapability('trae')?.model?.source).toBe('catalog');});+ it('keeps non-OpenAI Codex relay support on an explicit allowlist', () => {+ expect(CODEX_SERVER_DEFAULT_CUSTOM_MODELS).toEqual([+ 'deepseek-v4-flash',+ 'deepseek-v4-pro',+ 'glm-5.2',+ ]);+ expect(isCodexServerDefaultCustomModel('deepseek-v4-pro')).toBe(true);+ expect(isCodexServerDefaultCustomModel('kimi-k2.6')).toBe(false);+ });+it('reports codex effort levels per model', () => {const levels = getHeteroSelectorCapability('codex')?.effort?.levels;diff --git a/packages/types/src/agent/heteroSelectorCapabilities.ts b/packages/types/src/agent/heteroSelectorCapabilities.tsindex 419196b3db6..a362407bec2 100644--- a/packages/types/src/agent/heteroSelectorCapabilities.ts+++ b/packages/types/src/agent/heteroSelectorCapabilities.ts@@ -55,6 +55,23 @@ export type CodexReasoningEffort = (typeof CODEX_REASONING_EFFORT_LEVELS)[numberexport const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';+/**+ * Non-OpenAI models explicitly supported through a model-specific Codex catalog+ * and the deployment-owned server-default relay. Keep this list explicit: tool+ * support alone does not prove that Codex's request and continuation behavior+ * is compatible.+ */+export const CODEX_SERVER_DEFAULT_CUSTOM_MODELS = [+ 'deepseek-v4-flash',+ 'deepseek-v4-pro',+ 'glm-5.2',+] as const;++export type CodexServerDefaultCustomModel = (typeof CODEX_SERVER_DEFAULT_CUSTOM_MODELS)[number];++const CODEX_DEEPSEEK_V4_REASONING_EFFORT_LEVELS = ['low', 'high', 'max'] as const;+const CODEX_GLM_5_2_REASONING_EFFORT_LEVELS = ['high', 'max'] as const;+const CODEX_MAX_REASONING_EFFORT_LEVELS = [...CODEX_COMMON_REASONING_EFFORT_LEVELS,'max',@@ -126,6 +143,11 @@ export const isClaudeCodeReasoningEffort = (export const isCodexReasoningEffort = (value: string | undefined): value is CodexReasoningEffort =>!!value && CODEX_REASONING_EFFORT_LEVELS.includes(value as CodexReasoningEffort);+export const isCodexServerDefaultCustomModel = (+ model: string,+): model is CodexServerDefaultCustomModel =>+ CODEX_SERVER_DEFAULT_CUSTOM_MODELS.includes(model as CodexServerDefaultCustomModel);+export const isGrokBuildReasoningEffort = (value: string | undefined,): value is GrokBuildReasoningEffort =>@@ -144,6 +166,12 @@ export const isCodexFastServiceTier = (value: string | undefined): boolean =>* cannot be known until the CLI resolves the model.*/export const getCodexReasoningEffortLevels = (model: string): readonly CodexReasoningEffort[] => {+ if (model === 'deepseek-v4-flash' || model === 'deepseek-v4-pro') {+ return CODEX_DEEPSEEK_V4_REASONING_EFFORT_LEVELS;+ }++ if (model === 'glm-5.2') return CODEX_GLM_5_2_REASONING_EFFORT_LEVELS;+if (CODEX_ULTRA_REASONING_MODELS.includes(model as (typeof CODEX_ULTRA_REASONING_MODELS)[number])) {