🤯 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(agent): support Claude Code and Codex model selectors (#16199)
AmAzing-32746a571212
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex e27183fa833..6df82122444 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -387,6 +387,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {const ack = await spawnHeteroAgentRun({agentType: request.agentType,+ args: request.args,cwd: request.cwd,imageList: request.imageList,jwt: request.jwt,diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex db26c8637b6..d4a664aa201 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -192,6 +192,73 @@ describe('hetero exec command', () => {expect(call.operationId).toBe('op-server-allocated');});+ it('passes Claude Code --model and --effort through as spawnAgent extraArgs', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'claude-code',+ '--prompt',+ 'hi',+ '--model',+ 'opus',+ '--effort',+ 'high',+ ]);++ expect(mockSpawnAgent).toHaveBeenCalledTimes(1);+ expect(mockSpawnAgent.mock.calls[0][0]).toMatchObject({+ extraArgs: ['--model', 'opus', '--effort', 'high'],+ });+ });++ it('translates Codex --effort to native model_reasoning_effort config', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'codex',+ '--prompt',+ 'hi',+ '--model',+ 'gpt-5.5',+ '--effort',+ 'xhigh',+ ]);++ expect(mockSpawnAgent).toHaveBeenCalledTimes(1);+ expect(mockSpawnAgent.mock.calls[0][0]).toMatchObject({+ extraArgs: ['--model', 'gpt-5.5', '-c', 'model_reasoning_effort="xhigh"'],+ });+ });++ it('passes native agent args through --agent-arg without treating them as wrapper options', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'codex',+ '--prompt',+ 'hi',+ '--agent-arg=-c',+ '--agent-arg=model = "gpt-5.4"',+ '--effort',+ 'xhigh',+ ]);++ expect(mockSpawnAgent).toHaveBeenCalledTimes(1);+ expect(mockSpawnAgent.mock.calls[0][0]).toMatchObject({+ command: undefined,+ extraArgs: ['-c', 'model = "gpt-5.4"', '-c', 'model_reasoning_effort="xhigh"'],+ });+ });+it('streams events to stdout as JSONL, one line per event', async () => {const events = [{ data: { foo: 1 }, operationId: 'op-1', stepIndex: 0, timestamp: 1, type: 'stream_start' },diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex 4b2f87dba1b..74cf48df61d 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -18,6 +18,7 @@ import { log } from '../utils/logger';import { TrpcIngestSink } from '../utils/TrpcIngestSink';const SUPPORTED_AGENT_TYPES = new Set(['claude-code', 'codex']);+const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';/*** Patterns that indicate a `--resume <sessionId>` run should be retried@@ -54,10 +55,13 @@ const looksLikeNeedsRetryWithoutResume = (text: string): boolean =>RESUME_RETRY_PATTERNS.some((p) => p.test(text));interface ExecOptions {+ agentArg?: string[];command?: string;cwd?: string;+ effort?: string;image?: string[];inputJson?: string;+ model?: string;operationId?: string;prompt?: string;/**@@ -86,6 +90,27 @@ interface ExecOptions {}const collectImage = (value: string, previous: string[] = []): string[] => [...previous, value];+const collectAgentArg = (value: string, previous: string[] = []): string[] => [...previous, value];++const buildExtraArgs = (+ options: Pick<ExecOptions, 'agentArg' | 'effort' | 'model' | 'type'>,+): string[] | undefined => {+ const selectorArgs =+ options.type === 'codex'+ ? [+ ...(options.model ? ['--model', options.model] : []),+ ...(options.effort+ ? ['-c', `${CODEX_REASONING_EFFORT_CONFIG_KEY}="${options.effort}"`]+ : []),+ ]+ : [+ ...(options.model ? ['--model', options.model] : []),+ ...(options.effort ? ['--effort', options.effort] : []),+ ];+ const extraArgs = [...(options.agentArg ?? []), ...selectorArgs];++ return extraArgs.length > 0 ? extraArgs : undefined;+};const readStdin = async (): Promise<string> => {const chunks: Buffer[] = [];@@ -638,11 +663,13 @@ const exec = async (options: ExecOptions): Promise<void> => {// ─── First run (with --resume if provided) ───────────────────────────────const interceptResume = !!options.resume;+ const extraArgs = buildExtraArgs(options);const first = await runOneAgent({agentType: options.type,command: options.command,cwd: options.cwd || process.cwd(),+ extraArgs,operationId,prompt: resolved.prompt,resumeSessionId: options.resume,@@ -672,6 +699,7 @@ const exec = async (options: ExecOptions): Promise<void> => {agentType: options.type,command: options.command,cwd: options.cwd || process.cwd(),+ extraArgs,operationId,prompt: resolved.prompt,// No resumeSessionId — start fresh@@ -756,6 +784,13 @@ export function registerHeteroCommand(program: Command) {).option('-r, --resume <sessionId>', 'Resume an existing agent session by its native id').option('-d, --cwd <path>', 'Working directory for the spawned agent (default: process.cwd())')+ .option('--model <model>', 'Forward a resolved model selection to the agent CLI')+ .option('--effort <level>', 'Forward a resolved reasoning effort selection to the agent CLI')+ .option(+ '--agent-arg <arg>',+ 'Forward one native agent CLI argument after wrapper parsing (repeatable)',+ collectAgentArg,+ ).option('-c, --command <bin>','Override the agent CLI binary name (default: `claude` or `codex`)',diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.tsindex fe756b9a9d8..c7546a4c2bb 100644--- a/apps/cli/src/device/agentRun.test.ts+++ b/apps/cli/src/device/agentRun.test.ts@@ -103,6 +103,19 @@ describe('spawnHeteroAgentRun', () => {expect(args).toContain('sess-9');});+ it('forwards resolved args to lh hetero exec', () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);++ void spawnHeteroAgentRun({+ ...baseParams,+ args: ['--model', 'opus', '--effort', 'high'],+ });++ const [, args] = spawnMock.mock.calls[0];+ expect(args.slice(-4)).toEqual(['--model', 'opus', '--effort', 'high']);+ });+it('sends a content-block array to stdin when systemContext is provided', async () => {const child = makeFakeChild();spawnMock.mockReturnValue(child);diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex 1bbe8ee3d2c..493207499cc 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -7,6 +7,8 @@ import {export interface SpawnHeteroAgentRunParams {agentType: string;+ /** Resolved `lh hetero exec` wrapper args. */+ args?: string[];cwd?: string;/** Image attachments (signed URLs) appended as image content blocks. */imageList?: HeteroExecImageRef[];@@ -52,6 +54,7 @@ export function spawnHeteroAgentRun(): Promise<AgentRunAckResult> {const {agentType,+ args: extraArgs,cwd,imageList,jwt,@@ -83,6 +86,7 @@ export function spawnHeteroAgentRun('--cwd',workDir,...(resumeSessionId ? ['--resume', resumeSessionId] : []),+ ...(extraArgs ?? []),];// systemContext / image attachments turn the payload into a content-blockdiff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 00f7e48c668..c8eb4a0ddfa 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -297,6 +297,7 @@ export default class GatewayConnectionCtr extends ControllerModule {// Same command as spawnHeteroSandbox() on the server side.this.heterogeneousAgentCtr.spawnLhHeteroExec({agentType: request.agentType,+ args: request.args,cwd: request.cwd,imageList: request.imageList,jwt: request.jwt,diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 707e2ff976b..bbae4787a27 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -1471,6 +1471,8 @@ export default class HeterogeneousAgentCtr extends ControllerModule {*/spawnLhHeteroExec(params: {agentType: string;+ /** Resolved `lh hetero exec` wrapper args. */+ args?: string[];cwd?: string;/** Image attachments (signed URLs) appended as image content blocks. */imageList?: HeteroExecImageRef[];@@ -1484,6 +1486,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {}): void {const {agentType,+ args: extraArgs,cwd,imageList,jwt,@@ -1521,6 +1524,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {workDir,...(resumeSessionId ? ['--resume', resumeSessionId] : []),...(rawDumpDir ? ['--raw-dump', rawDumpDir] : []),+ ...(extraArgs ?? []),];const env = {diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex e461271fb5d..1c9ea046827 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -861,6 +861,20 @@ describe('GatewayConnectionCtr', () => {);});+ it('forwards resolved selector args from the request to spawnLhHeteroExec', async () => {+ const client = await connectAndOpen();+ client.simulateAgentRunRequest('claude-code', 'op-args', 'hi', 'mock-jwt', {+ args: ['--model', 'opus', '--effort', 'high'],+ });+ await vi.advanceTimersByTimeAsync(0);++ expect(mockHeterogeneousAgentCtr.spawnLhHeteroExec).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--model', 'opus', '--effort', 'high'],+ }),+ );+ });+it('sends accepted ack and spawns lh hetero exec', async () => {const client = await connectAndOpen();client.simulateAgentRunRequest('openclaw', 'op-xyz');diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex a8db64518f1..4ce1c4cf930 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -3,11 +3,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';const {+ mockDeviceFindByDeviceId,+ mockDeviceFindWorkspaceDeviceById,+ mockDispatchAgentRun,mockMessageCreate,mockResolveAttachmentsByFileIds,mockSpawnHeteroSandbox,mockIngestAttachment,} = vi.hoisted(() => ({+ mockDeviceFindByDeviceId: vi.fn(),+ mockDeviceFindWorkspaceDeviceById: vi.fn(),+ mockDispatchAgentRun: vi.fn().mockResolvedValue({ success: true }),mockIngestAttachment: vi.fn(),mockMessageCreate: vi.fn(),mockResolveAttachmentsByFileIds: vi.fn(),@@ -68,6 +74,13 @@ vi.mock('@/database/models/agent', () => ({})),}));+vi.mock('@/database/models/device', () => ({+ DeviceModel: vi.fn().mockImplementation(() => ({+ findByDeviceId: mockDeviceFindByDeviceId,+ findWorkspaceDeviceById: mockDeviceFindWorkspaceDeviceById,+ })),+}));+vi.mock('@/server/services/agent', () => ({AgentService: vi.fn().mockImplementation(() => ({getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),@@ -150,11 +163,17 @@ vi.mock('@/server/modules/Mecha', () => ({vi.mock('@/server/services/deviceGateway', () => ({deviceGateway: {+ dispatchAgentRun: mockDispatchAgentRun,isConfigured: false,queryDeviceList: vi.fn().mockResolvedValue([]),+ resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),},}));+vi.mock('@/server/services/heterogeneousAgent/remoteDeviceHeteroContext', () => ({+ buildRemoteDeviceHeteroContext: vi.fn().mockReturnValue('device context'),+}));+describe('AiAgentService.execAgent - hetero early-exit file attachments', () => {let service: AiAgentService;const mockDb = {} as any;@@ -168,7 +187,13 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>mockMessageCreate.mockResolvedValue({ id: 'msg-1' });mockResolveAttachmentsByFileIds.mockResolvedValue({ ...emptyResolvedAttachments });mockSpawnHeteroSandbox.mockResolvedValue(undefined);+ mockDispatchAgentRun.mockResolvedValue({ success: true });+ mockDeviceFindByDeviceId.mockResolvedValue({ defaultCwd: '/Users/alice/repo' });+ mockDeviceFindWorkspaceDeviceById.mockResolvedValue(undefined);mockIngestAttachment.mockReset();+ heteroAgentConfig.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } } as any;+ heteroAgentConfig.model = 'claude-code';+ heteroAgentConfig.provider = 'anthropic';service = new AiAgentService(mockDb, userId);});@@ -244,6 +269,89 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>expect(userCall![0].files).toBeUndefined();});+ it('should pass resolved Claude Code model and effort args to sandbox dispatch', async () => {+ heteroAgentConfig.agencyConfig.heterogeneousProvider = {+ effort: 'high',+ model: 'opus',+ type: 'claude-code',+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Use the selected Claude Code model',+ });++ expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--model', 'opus', '--effort', 'high'],+ }),+ );+ });++ it('should pass resolved Codex model and reasoning effort args to sandbox dispatch', async () => {+ heteroAgentConfig.model = 'codex';+ heteroAgentConfig.provider = 'codex';+ heteroAgentConfig.agencyConfig.heterogeneousProvider = {+ effort: 'xhigh',+ model: 'gpt-5.5',+ type: 'codex',+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Use the selected Codex model',+ });++ expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--model', 'gpt-5.5', '--effort', 'xhigh'],+ }),+ );+ });++ it('should encode native Codex args before forwarding them to sandbox lh hetero exec', async () => {+ heteroAgentConfig.model = 'codex';+ heteroAgentConfig.provider = 'codex';+ heteroAgentConfig.agencyConfig.heterogeneousProvider = {+ args: ['-c', 'model = "gpt-5.4"'],+ effort: 'xhigh',+ model: 'gpt-5.5',+ type: 'codex',+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Use existing native Codex args',+ });++ expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--agent-arg=-c', '--agent-arg=model = "gpt-5.4"', '--effort', 'xhigh'],+ }),+ );+ });++ it('should not pass selector args to device dispatch without capability gating', async () => {+ heteroAgentConfig.agencyConfig = {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: {+ effort: 'high',+ model: 'opus',+ type: 'claude-code',+ },+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Use the selected Claude Code model on device',+ });++ const dispatchParams = mockDispatchAgentRun.mock.calls[0][0];+ expect(dispatchParams).toEqual(expect.objectContaining({ deviceId: 'device-1' }));+ expect(dispatchParams).not.toHaveProperty('args');+ });+describe('image delivery to the dispatched CLI', () => {it('should resolve image attachments and pass imageList to the sandbox dispatch', async () => {mockResolveAttachmentsByFileIds.mockResolvedValue({diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex e54f836be8e..002e5f6d924 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -43,7 +43,7 @@ import type {UserInterventionConfig,WorkspaceInitResult,} from '@lobechat/types';-import { RequestTrigger, ThreadStatus, ThreadType } from '@lobechat/types';+import { buildHeteroExecArgs, RequestTrigger, ThreadStatus, ThreadType } from '@lobechat/types';import { nanoid } from '@lobechat/utils';import debug from 'debug';@@ -1325,6 +1325,14 @@ export class AiAgentService {runAttachments.imageList && runAttachments.imageList.length > 0? runAttachments.imageList.map((image) => ({ id: image.id, url: image.url })): undefined;+ const heteroExecArgs =+ heteroType === 'claude-code' || heteroType === 'codex'+ ? buildHeteroExecArgs(+ agentConfig.agencyConfig?.heterogeneousProvider?.type === heteroType+ ? agentConfig.agencyConfig.heterogeneousProvider+ : { type: heteroType },+ )+ : undefined;const heteroParams = {agentType: heteroType,@@ -1634,6 +1642,7 @@ export class AiAgentService {spawnHeteroSandbox({...heteroParams,agentType: heteroType as 'claude-code' | 'codex',+ args: heteroExecArgs,marketService: this.marketService,}).catch((err) => {log('execAgent: hetero sandbox spawn failed: %O', err);diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex a529977c19b..83d34ee3fe2 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -930,6 +930,8 @@ export class DeviceGateway {async dispatchAgentRun(params: {agentType: HeterogeneousAgentType;+ /** Resolved `lh hetero exec` wrapper args. */+ args?: string[];cwd?: string;deviceId?: string;/** Image attachments forwarded to the device as fetchable (signed) URLs. */diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.tsnew file mode 100644index 00000000000..63927975304--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts@@ -0,0 +1,64 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { spawnHeteroSandbox } from '../sandboxRunner';++const { mockCallTool } = vi.hoisted(() => ({+ mockCallTool: vi.fn().mockResolvedValue({ success: true }),+}));++vi.mock('@/envs/app', () => ({+ appEnv: { APP_URL: 'https://app.example.com' },+}));++vi.mock('@/server/services/sandbox', () => ({+ createSandboxService: vi.fn(() => ({+ callTool: mockCallTool,+ })),+}));++describe('spawnHeteroSandbox', () => {+ beforeEach(() => {+ mockCallTool.mockClear();+ mockCallTool.mockResolvedValue({ success: true });+ });++ it('forwards resolved selector args to lh hetero exec', async () => {+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ args: ['--model', 'opus', '--effort', 'high'],+ assistantMessageId: 'msg-1',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(mockCallTool).toHaveBeenCalledWith(+ 'runCommand',+ expect.objectContaining({+ command: expect.stringContaining("'--model' 'opus' '--effort' 'high'"),+ }),+ );+ });++ it('shell-escapes selector args before interpolating the sandbox command', async () => {+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ args: ['--model', '$(touch /tmp/pwned)', '--effort', "hi'there"],+ assistantMessageId: 'msg-1',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ const command = mockCallTool.mock.calls[0][1].command;+ expect(command).toContain("'$(touch /tmp/pwned)'");+ expect(command).toContain("'hi'\\''there'");+ expect(command).not.toContain('"$(touch /tmp/pwned)"');+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.tsindex 536eec91684..0ccaf04caac 100644--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts@@ -14,8 +14,12 @@ import { createSandboxService } from '@/server/services/sandbox';const log = debug('lobe-server:hetero-sandbox-runner');+const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;+export interface SandboxRunParams {agentType: 'claude-code' | 'codex';+ /** Resolved `lh hetero exec` wrapper args. */+ args?: string[];/** Initial assistant placeholder message id — injected as LOBEHUB_ASSISTANT_MESSAGE_ID so* the CLI can pass it through the heteroIngest payload, removing the need for the server* to re-read topic.metadata.runningOperation on every cold Lambda start. */@@ -71,15 +75,15 @@ function repoToLocalDir(repo: string): string {*/function buildCredsSetupScript(githubToken?: string): string | null {if (!githubToken) return null;- const tokenJson = JSON.stringify(githubToken);+ const tokenArg = shellQuote(githubToken);return ['mkdir -p ~/.creds',// Write GITHUB_ACCESS_TOKEN matching the injectCredsToSandbox oauth naming scheme- `printf 'GITHUB_ACCESS_TOKEN=%s\\n' ${tokenJson} > ~/.creds/env`,+ `printf 'GITHUB_ACCESS_TOKEN=%s\\n' ${tokenArg} > ~/.creds/env`,// Pre-authenticate gh CLI so CC can use it immediately (gh also picks up// GITHUB_TOKEN from env, but explicit login ensures ~/.config/gh/hosts.yml// is populated for cases where env is reset in a sub-shell)- `echo ${tokenJson} | gh auth login --hostname github.com --with-token 2>/dev/null || true`,+ `echo ${tokenArg} | gh auth login --hostname github.com --with-token 2>/dev/null || true`,].join(' && \\\n');}@@ -97,12 +101,16 @@ function buildRepoSetupScript(repos: string[], githubToken?: string): string | nconst repoPath = repo.startsWith('http') ? (repo.split('github.com/')[1] ?? repo) : repo;// Use git's insteadOf rewrite (passed via -c, not stored in .git/config) so the token// never ends up in the cloned repo's remote URL.+ const dirArg = shellQuote(dir);+ const repoUrlArg = shellQuote(`https://github.com/${repoPath}`);const cloneCmd = githubToken- ? `git -c "url.https://oauth2:${githubToken}@github.com/.insteadOf=https://github.com/" clone -q https://github.com/${repoPath} '${dir}'`- : `git clone -q 'https://github.com/${repoPath}' '${dir}'`;+ ? `git -c ${shellQuote(+ `url.https://oauth2:${githubToken}@github.com/.insteadOf=https://github.com/`,+ )} clone -q ${repoUrlArg} ${dirArg}`+ : `git clone -q ${repoUrlArg} ${dirArg}`;// `|| true` makes clone failures non-fatal — CC still runs even if a repo can't be cloned.- return `{ [ -d '${dir}' ] || ${cloneCmd}; } || true`;+ return `{ [ -d ${dirArg} ] || ${cloneCmd}; } || true`;});return lines.join(' && \\\n');@@ -124,6 +132,7 @@ function buildRepoSetupScript(repos: string[], githubToken?: string): string | nexport async function spawnHeteroSandbox(params: SandboxRunParams): Promise<void> {const {agentType,+ args: extraArgs,assistantMessageId,githubToken,jwt,@@ -164,6 +173,7 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<voidargs.push('--resume', resumeSessionId);}args.push('--cwd', cwd);+ args.push(...(extraArgs ?? []));// Encode the prompt as base64 to avoid all shell quoting issues.// echo + shell quoting mangled inner JSON quotes; base64 is quote-safe.@@ -182,14 +192,15 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<void// auth callbacks and must stay as localhost in dev.const serverUrl = process.env.LOBEHUB_HETERO_SERVER_URL ?? appEnv.APP_URL;const envVars = [- `LOBEHUB_JWT=${JSON.stringify(jwt)}`,- `LOBEHUB_SERVER=${JSON.stringify(serverUrl)}`,- `LOBEHUB_ASSISTANT_MESSAGE_ID=${JSON.stringify(assistantMessageId)}`,+ `LOBEHUB_JWT=${shellQuote(jwt)}`,+ `LOBEHUB_SERVER=${shellQuote(serverUrl)}`,+ `LOBEHUB_ASSISTANT_MESSAGE_ID=${shellQuote(assistantMessageId)}`,// Inject GitHub token so CC can authenticate git operations and GitHub API// calls inside the sandbox (e.g. gh CLI, git push, API requests).- ...(githubToken ? [`GITHUB_TOKEN=${JSON.stringify(githubToken)}`] : []),+ ...(githubToken ? [`GITHUB_TOKEN=${shellQuote(githubToken)}`] : []),].join(' ');- const mainCommand = `echo ${base64Payload} | base64 -d | ${envVars} ${args.join(' ')}`;+ const shellArgs = args.map(shellQuote).join(' ');+ const mainCommand = `echo ${shellQuote(base64Payload)} | base64 -d | ${envVars} ${shellArgs}`;// Creds first (writes ~/.creds/env + authenticates gh CLI), then repo clone.const credsScript = buildCredsSetupScript(githubToken);const repoScript = buildRepoSetupScript(repos ?? [], githubToken);diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex db73db6d5d1..0aa80b394ad 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -257,7 +257,19 @@"heteroAgent.executionTarget.unknownDevice": "Unknown device","heteroAgent.executionTarget.workspaceGroup": "Workspace","heteroAgent.fullAccess.label": "Full access",- "heteroAgent.fullAccess.tooltip": "Claude Code runs locally with full read/write access to the working directory. Switching permission modes is not available yet.",+ "heteroAgent.fullAccess.tooltip": "The local coding agent runs with full read/write access to the working directory. Switching permission modes is not available yet.",+ "heteroAgent.modelSelector.ariaLabel": "Model: {{model}}. Reasoning: {{reasoning}}",+ "heteroAgent.modelSelector.default": "Default",+ "heteroAgent.modelSelector.defaultConfig": "Default config",+ "heteroAgent.modelSelector.defaultModel": "Default model",+ "heteroAgent.modelSelector.defaultReasoning": "Default effort",+ "heteroAgent.modelSelector.model": "Model",+ "heteroAgent.modelSelector.reasoning": "Reasoning",+ "heteroAgent.modelSelector.reasoning.high": "High",+ "heteroAgent.modelSelector.reasoning.low": "Low",+ "heteroAgent.modelSelector.reasoning.max": "Max",+ "heteroAgent.modelSelector.reasoning.medium": "Medium",+ "heteroAgent.modelSelector.reasoning.xhigh": "Extra High","heteroAgent.resumeReset.cwdChanged": "Working directory changed. Previous Claude Code session can only be resumed from its original directory, so a new conversation has started.","heteroAgent.resumeReset.resumeFailed": "The saved Codex thread could not be resumed safely, so a new conversation has started for this topic.","heteroAgent.switchCwd.cancel": "Cancel",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 6f6de635261..39efc15576d 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -257,7 +257,19 @@"heteroAgent.executionTarget.unknownDevice": "未知设备","heteroAgent.executionTarget.workspaceGroup": "工作区设备","heteroAgent.fullAccess.label": "完全访问权限",- "heteroAgent.fullAccess.tooltip": "Claude Code 在本地运行,对工作目录拥有完全的读写权限。当前暂不支持切换权限模式。",+ "heteroAgent.fullAccess.tooltip": "本地编码 Agent 运行时对工作目录拥有完全的读写权限。当前暂不支持切换权限模式。",+ "heteroAgent.modelSelector.ariaLabel": "模型:{{model}}。思考强度:{{reasoning}}",+ "heteroAgent.modelSelector.default": "默认",+ "heteroAgent.modelSelector.defaultConfig": "默认配置",+ "heteroAgent.modelSelector.defaultModel": "默认模型",+ "heteroAgent.modelSelector.defaultReasoning": "默认强度",+ "heteroAgent.modelSelector.model": "模型",+ "heteroAgent.modelSelector.reasoning": "思考强度",+ "heteroAgent.modelSelector.reasoning.high": "高",+ "heteroAgent.modelSelector.reasoning.low": "低",+ "heteroAgent.modelSelector.reasoning.max": "最高",+ "heteroAgent.modelSelector.reasoning.medium": "中",+ "heteroAgent.modelSelector.reasoning.xhigh": "超高","heteroAgent.resumeReset.cwdChanged": "工作目录已切换,之前的 Claude Code 会话只能在原目录下继续,已开始新对话。","heteroAgent.resumeReset.resumeFailed": "已保存的 Codex 线程无法安全恢复,当前话题已自动开启新会话。","heteroAgent.switchCwd.cancel": "取消",diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex f1df0c1b583..917885d50b2 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -200,6 +200,8 @@ export class GatewayHttpClient {async dispatchAgentRun(params: {agentType: string;+ /** Resolved `lh hetero exec` wrapper args. */+ args?: string[];cwd?: string;deviceId?: string;/** Image attachments forwarded into the `agent_run_request` message. */diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex 5a729ccf222..28b3b927589 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -195,6 +195,12 @@ export interface RpcResponseMessage {/** Server → Client: request the desktop to spawn `lh hetero exec`. */export interface AgentRunRequestMessage {agentType: string;+ /**+ * Resolved `lh hetero exec` wrapper args, e.g. `--model` / `--effort`.+ * Optional for protocol+ * compatibility with older servers.+ */+ args?: string[];cwd?: string;/*** Image attachments from the user message, as URLs the device can fetchdiff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 2f8775fccf0..f40d12390ac 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -171,7 +171,19 @@ export default {'groupWizard.useTemplate': 'Use Template','heteroAgent.fullAccess.label': 'Full access','heteroAgent.fullAccess.tooltip':- 'Claude Code runs locally with full read/write access to the working directory. Switching permission modes is not available yet.',+ 'The local coding agent runs with full read/write access to the working directory. Switching permission modes is not available yet.',+ 'heteroAgent.modelSelector.ariaLabel': 'Model: {{model}}. Reasoning: {{reasoning}}',+ 'heteroAgent.modelSelector.default': 'Default',+ 'heteroAgent.modelSelector.defaultConfig': 'Default config',+ 'heteroAgent.modelSelector.defaultModel': 'Default model',+ 'heteroAgent.modelSelector.defaultReasoning': 'Default effort',+ 'heteroAgent.modelSelector.model': 'Model',+ 'heteroAgent.modelSelector.reasoning': 'Reasoning',+ 'heteroAgent.modelSelector.reasoning.high': 'High',+ 'heteroAgent.modelSelector.reasoning.low': 'Low',+ 'heteroAgent.modelSelector.reasoning.max': 'Max',+ 'heteroAgent.modelSelector.reasoning.medium': 'Medium',+ 'heteroAgent.modelSelector.reasoning.xhigh': 'Extra High','heteroAgent.resumeReset.cwdChanged':'Working directory changed. Previous Claude Code session can only be resumed from its original directory, so a new conversation has started.','heteroAgent.resumeReset.resumeFailed':diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.tsindex 6415ce3e762..ea8a72ff3ee 100644--- a/packages/types/src/agent/agencyConfig.test.ts+++ b/packages/types/src/agent/agencyConfig.test.ts@@ -1,6 +1,15 @@import { describe, expect, it } from 'vitest';-import { pruneWorkingDirByDeviceDeletes } from './agencyConfig';+import {+ buildHeteroExecArgs,+ buildHeteroSpawnArgs,+ HETEROGENEOUS_AGENT_DEFAULT_SELECTION,+ pruneWorkingDirByDeviceDeletes,+ resolveClaudeCodeModel,+ resolveClaudeCodeReasoningEffort,+ resolveCodexModel,+ resolveCodexReasoningEffort,+} from './agencyConfig';describe('pruneWorkingDirByDeviceDeletes', () => {it('deletes keys whose patch value is undefined', () => {@@ -32,3 +41,206 @@ describe('pruneWorkingDirByDeviceDeletes', () => {).not.toThrow();});});++describe('buildHeteroSpawnArgs', () => {+ it('resolves missing Claude Code selections to Default', () => {+ expect(resolveClaudeCodeModel(undefined)).toBe(HETEROGENEOUS_AGENT_DEFAULT_SELECTION);+ expect(resolveClaudeCodeReasoningEffort(undefined)).toBe(HETEROGENEOUS_AGENT_DEFAULT_SELECTION);+ });++ it('resolves missing Codex selections to Default', () => {+ expect(resolveCodexModel(undefined)).toBe(HETEROGENEOUS_AGENT_DEFAULT_SELECTION);+ expect(resolveCodexReasoningEffort(undefined)).toBe(HETEROGENEOUS_AGENT_DEFAULT_SELECTION);+ });++ it('returns undefined when there is no provider', () => {+ expect(buildHeteroSpawnArgs(undefined)).toBeUndefined();+ expect(buildHeteroSpawnArgs(null)).toBeUndefined();+ });++ it('leaves remote providers untouched', () => {+ expect(buildHeteroSpawnArgs({ args: ['--agent', 'main'], type: 'openclaw' })).toEqual([+ '--agent',+ 'main',+ ]);+ });++ it('preserves Claude Code defaults when model/effort have not been selected', () => {+ expect(buildHeteroSpawnArgs({ type: 'claude-code' })).toBeUndefined();+ expect(buildHeteroSpawnArgs({ args: ['--verbose'], type: 'claude-code' })).toEqual([+ '--verbose',+ ]);+ // Older persisted "Default" selections should behave like unset values.+ expect(+ buildHeteroSpawnArgs({+ effort: HETEROGENEOUS_AGENT_DEFAULT_SELECTION,+ model: HETEROGENEOUS_AGENT_DEFAULT_SELECTION,+ type: 'claude-code',+ }),+ ).toBeUndefined();+ });++ it('preserves Codex defaults when model/effort have not been selected', () => {+ expect(buildHeteroSpawnArgs({ type: 'codex' })).toBeUndefined();+ expect(buildHeteroSpawnArgs({ args: ['--ask-for-approval', 'never'], type: 'codex' })).toEqual([+ '--ask-for-approval',+ 'never',+ ]);+ expect(+ buildHeteroSpawnArgs({+ effort: HETEROGENEOUS_AGENT_DEFAULT_SELECTION,+ model: HETEROGENEOUS_AGENT_DEFAULT_SELECTION,+ type: 'codex',+ }),+ ).toBeUndefined();+ });++ it('appends --model and --effort for claude-code', () => {+ expect(buildHeteroSpawnArgs({ type: 'claude-code', model: 'opus', effort: 'high' })).toEqual([+ '--model',+ 'opus',+ '--effort',+ 'high',+ ]);+ });++ it('preserves existing args and appends after them', () => {+ expect(+ buildHeteroSpawnArgs({ args: ['--verbose'], type: 'claude-code', model: 'sonnet' }),+ ).toEqual(['--verbose', '--model', 'sonnet']);+ });++ it('only appends explicitly selected flags', () => {+ expect(buildHeteroSpawnArgs({ type: 'claude-code', effort: 'max' })).toEqual([+ '--effort',+ 'max',+ ]);+ expect(buildHeteroSpawnArgs({ type: 'claude-code', model: 'haiku' })).toEqual([+ '--model',+ 'haiku',+ ]);+ });++ it('does not duplicate a flag the user already authored in args', () => {+ // space-separated form+ expect(+ buildHeteroSpawnArgs({+ args: ['--model', 'opus'],+ type: 'claude-code',+ model: 'sonnet',+ effort: 'high',+ }),+ ).toEqual(['--model', 'opus', '--effort', 'high']);+ // `--flag=value` form+ expect(+ buildHeteroSpawnArgs({+ args: ['--effort=low'],+ type: 'claude-code',+ model: 'opus',+ effort: 'high',+ }),+ ).toEqual(['--effort=low', '--model', 'opus']);+ });++ it('resolves Codex model and reasoning effort from args before persisted selections', () => {+ expect(+ resolveCodexModel({+ args: ['--model', 'gpt-5.4'],+ model: 'gpt-5.5',+ }),+ ).toBe('gpt-5.4');+ expect(+ resolveCodexModel({+ args: ['-c', 'model = "gpt-5.3-codex-spark"'],+ model: 'gpt-5.5',+ }),+ ).toBe('gpt-5.3-codex-spark');+ expect(+ resolveCodexReasoningEffort({+ args: ['--config=model_reasoning_effort="xhigh"'],+ effort: 'low',+ }),+ ).toBe('xhigh');+ });++ it('appends --model and model_reasoning_effort config for Codex', () => {+ expect(buildHeteroSpawnArgs({ type: 'codex', model: 'gpt-5.5', effort: 'high' })).toEqual([+ '--model',+ 'gpt-5.5',+ '-c',+ 'model_reasoning_effort="high"',+ ]);+ });++ it('does not duplicate Codex args the user already authored', () => {+ expect(+ buildHeteroSpawnArgs({+ args: ['-m', 'gpt-5.4'],+ effort: 'high',+ model: 'gpt-5.5',+ type: 'codex',+ }),+ ).toEqual(['-m', 'gpt-5.4', '-c', 'model_reasoning_effort="high"']);+ expect(+ buildHeteroSpawnArgs({+ args: ['--config=model_reasoning_effort="low"'],+ effort: 'high',+ model: 'gpt-5.5',+ type: 'codex',+ }),+ ).toEqual(['--config=model_reasoning_effort="low"', '--model', 'gpt-5.5']);+ expect(+ buildHeteroSpawnArgs({+ args: ['-c', 'model = "gpt-5.4"'],+ model: 'gpt-5.5',+ type: 'codex',+ }),+ ).toEqual(['-c', 'model = "gpt-5.4"']);+ });++ it('builds lh hetero exec wrapper args for Codex selectors', () => {+ expect(buildHeteroExecArgs({ type: 'codex', model: 'gpt-5.5', effort: 'high' })).toEqual([+ '--model',+ 'gpt-5.5',+ '--effort',+ 'high',+ ]);+ });++ it('does not append native Codex config flags to lh hetero exec args', () => {+ expect(+ buildHeteroExecArgs({+ args: ['-c', 'model = "gpt-5.4"'],+ effort: 'xhigh',+ type: 'codex',+ }),+ ).toEqual(['--agent-arg=-c', '--agent-arg=model = "gpt-5.4"', '--effort', 'xhigh']);+ });++ it('keeps Claude Code lh hetero exec selector args in the same wrapper form', () => {+ expect(buildHeteroExecArgs({ type: 'claude-code', model: 'opus', effort: 'high' })).toEqual([+ '--model',+ 'opus',+ '--effort',+ 'high',+ ]);+ });++ it('encodes native agent args before forwarding them to lh hetero exec', () => {+ expect(+ buildHeteroExecArgs({+ args: ['--ask-for-approval', 'never'],+ model: 'gpt-5.5',+ type: 'codex',+ }),+ ).toEqual(['--agent-arg=--ask-for-approval', '--agent-arg=never', '--model', 'gpt-5.5']);++ expect(+ buildHeteroExecArgs({+ args: ['--verbose'],+ effort: 'high',+ type: 'claude-code',+ }),+ ).toEqual(['--agent-arg=--verbose', '--effort', 'high']);+ });+});diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex 78abeb36a08..1cf87556084 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -1,3 +1,47 @@+/**+ * Selector value that means "do not override the underlying CLI".+ *+ * When persisted, it intentionally does not translate into CLI flags; the+ * underlying CLI keeps using its own settings, env vars, and account defaults.+ */+export const HETEROGENEOUS_AGENT_DEFAULT_SELECTION = 'default' as const;++export type HeterogeneousAgentDefaultSelection = typeof HETEROGENEOUS_AGENT_DEFAULT_SELECTION;++/**+ * Claude Code reasoning-effort levels, mirrored 1:1 with the CLI's+ * `--effort <level>` flag.+ */+export const CLAUDE_CODE_REASONING_EFFORT_LEVELS = [+ 'low',+ 'medium',+ 'high',+ 'xhigh',+ 'max',+] as const;++export type ClaudeCodeReasoningEffort = (typeof CLAUDE_CODE_REASONING_EFFORT_LEVELS)[number];++export const CLAUDE_CODE_DEFAULT_MODEL = 'sonnet';+export const CLAUDE_CODE_DEFAULT_REASONING_EFFORT = 'high' satisfies ClaudeCodeReasoningEffort;++/**+ * Codex reasoning-effort levels, mirrored to the CLI config key+ * `model_reasoning_effort`.+ */+export const CODEX_REASONING_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh'] as const;++export type CodexReasoningEffort = (typeof CODEX_REASONING_EFFORT_LEVELS)[number];++export const CODEX_DEFAULT_MODEL = 'gpt-5.5';+export const CODEX_DEFAULT_REASONING_EFFORT = 'medium' satisfies CodexReasoningEffort;+export const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';++export type HeterogeneousReasoningEffort =+ | ClaudeCodeReasoningEffort+ | CodexReasoningEffort+ | HeterogeneousAgentDefaultSelection;+/*** Heterogeneous agent provider configuration.* When set, the assistant delegates execution to an external agent runtime@@ -17,8 +61,23 @@ export interface HeterogeneousProviderConfig {args?: string[];/** Command to spawn the agent (e.g. 'claude') (local CLI only). */command?: string;+ /**+ * Reasoning effort, surfaced through the chat-input model selector and+ * translated into the provider-specific CLI flags/config at spawn time.+ * Omitted or `'default'` values are displayed as Default in the UI and are+ * not passed as CLI overrides, so the CLI can keep its own settings, env+ * vars, and account defaults.+ */+ effort?: HeterogeneousReasoningEffort;/** Custom environment variables (local CLI only). */env?: Record<string, string>;+ /**+ * CLI model, surfaced through the chat-input model selector and translated+ * into the provider-specific model override at spawn time. Empty / omitted+ * values are displayed as Default in the UI, but are not passed as CLI flags+ * so the CLI can keep its own settings, env vars, and account defaults.+ */+ model?: string;/*** Platform-side agent identifier used by remote device runtimes.* - openclaw: selects the named agent (defaults to `'main'`)@@ -36,6 +95,282 @@ export interface HeterogeneousProviderConfig {type: 'amp' | 'claude-code' | 'codex' | 'hermes' | 'opencode' | 'openclaw';}+interface ClaudeCodeSelectionSource {+ args?: string[];+ effort?: string | null;+ model?: string | null;+}++interface CodexSelectionSource {+ args?: string[];+ effort?: string | null;+ model?: string | null;+}++const CODEX_CONFIG_FLAGS = ['-c', '--config'] as const;+const CODEX_MODEL_FLAGS = ['-m', '--model'] as const;+const HETERO_EXEC_AGENT_ARG_FLAG = '--agent-arg';++const hasCliFlag = (args: string[], flag: string): boolean =>+ args.some((arg) => arg === flag || arg.startsWith(`${flag}=`));++const hasAnyCliFlag = (args: string[], flags: readonly string[]): boolean =>+ flags.some((flag) => hasCliFlag(args, flag));++const getCliFlagValue = (args: string[] | undefined, flag: string): string | undefined => {+ if (!args) return undefined;++ for (let index = 0; index < args.length; index += 1) {+ const arg = args[index];+ if (arg === flag) {+ const next = args[index + 1]?.trim();+ if (next && !next.startsWith('-')) return next;+ }++ const prefix = `${flag}=`;+ if (arg.startsWith(prefix)) {+ const value = arg.slice(prefix.length).trim();+ if (value) return value;+ }+ }++ return undefined;+};++const getAnyCliFlagValue = (+ args: string[] | undefined,+ flags: readonly string[],+): string | undefined => {+ for (const flag of flags) {+ const value = getCliFlagValue(args, flag);+ if (value) return value;+ }+};++const unquoteCliConfigValue = (value: string): string => {+ const trimmed = value.trim();+ const quote = trimmed[0];++ if ((quote === '"' || quote === "'") && trimmed.at(-1) === quote) {+ return trimmed.slice(1, -1);+ }++ return trimmed;+};++const escapeRegExp = (value: string): string => value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');++const parseCliConfigAssignment = (assignment: string, key: string): string | undefined => {+ const match = assignment.match(new RegExp(`^\\s*${escapeRegExp(key)}\\s*=\\s*(.+?)\\s*$`));+ if (!match?.[1]) return undefined;++ const value = unquoteCliConfigValue(match[1]);+ return value || undefined;+};++const getCliConfigValue = (args: string[] | undefined, key: string): string | undefined => {+ if (!args) return undefined;++ for (let index = 0; index < args.length; index += 1) {+ const arg = args[index];++ if (CODEX_CONFIG_FLAGS.includes(arg as (typeof CODEX_CONFIG_FLAGS)[number])) {+ const next = args[index + 1];+ if (next) {+ const value = parseCliConfigAssignment(next, key);+ if (value) return value;+ index += 1;+ }+ continue;+ }++ const configFlag = CODEX_CONFIG_FLAGS.find((flag) => arg.startsWith(`${flag}=`));+ if (configFlag) {+ const value = parseCliConfigAssignment(arg.slice(configFlag.length + 1), key);+ if (value) return value;+ }+ }+};++const hasCliConfigKey = (args: string[], key: string): boolean => !!getCliConfigValue(args, key);++const isClaudeCodeReasoningEffort = (+ value: string | undefined,+): value is ClaudeCodeReasoningEffort =>+ !!value && CLAUDE_CODE_REASONING_EFFORT_LEVELS.includes(value as ClaudeCodeReasoningEffort);++const isCodexReasoningEffort = (value: string | undefined): value is CodexReasoningEffort =>+ !!value && CODEX_REASONING_EFFORT_LEVELS.includes(value as CodexReasoningEffort);++export const resolveClaudeCodeModel = (+ source: ClaudeCodeSelectionSource | null | undefined,+): string => {+ const model = (getCliFlagValue(source?.args, '--model') ?? source?.model)?.trim();+ return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION+ ? model+ : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;+};++export const resolveClaudeCodeReasoningEffort = (+ source: ClaudeCodeSelectionSource | null | undefined,+): ClaudeCodeReasoningEffort | HeterogeneousAgentDefaultSelection => {+ const effort = (getCliFlagValue(source?.args, '--effort') ?? source?.effort)?.trim();+ return isClaudeCodeReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;+};++const getExplicitClaudeCodeModel = (+ source: ClaudeCodeSelectionSource | null | undefined,+): string | undefined => {+ const model = source?.model?.trim();+ return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION ? model : undefined;+};++const getExplicitClaudeCodeReasoningEffort = (+ source: ClaudeCodeSelectionSource | null | undefined,+): ClaudeCodeReasoningEffort | undefined => {+ const effort = source?.effort?.trim();+ return isClaudeCodeReasoningEffort(effort) ? effort : undefined;+};++export const resolveCodexModel = (source: CodexSelectionSource | null | undefined): string => {+ const model = (+ getAnyCliFlagValue(source?.args, CODEX_MODEL_FLAGS) ??+ getCliConfigValue(source?.args, 'model') ??+ source?.model+ )?.trim();++ return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION+ ? model+ : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;+};++export const resolveCodexReasoningEffort = (+ source: CodexSelectionSource | null | undefined,+): CodexReasoningEffort | HeterogeneousAgentDefaultSelection => {+ const effort = (+ getCliConfigValue(source?.args, CODEX_REASONING_EFFORT_CONFIG_KEY) ?? source?.effort+ )?.trim();++ return isCodexReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;+};++const getExplicitCodexModel = (+ source: CodexSelectionSource | null | undefined,+): string | undefined => {+ const model = source?.model?.trim();+ return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION ? model : undefined;+};++const getExplicitCodexReasoningEffort = (+ source: CodexSelectionSource | null | undefined,+): CodexReasoningEffort | undefined => {+ const effort = source?.effort?.trim();+ return isCodexReasoningEffort(effort) ? effort : undefined;+};++/**+ * Resolve the effective native CLI args for a heterogeneous spawn.+ *+ * For `claude-code` and `codex`, the chat-input selector persists explicit+ * `model` + `effort` selections on the provider config; this is the single+ * place that maps those stored settings onto provider-specific argv for direct+ * local desktop spawns.+ * Missing/default settings are resolved by the UI helpers for display only.+ * They are not appended here because CLI overrides must not mask each CLI's+ * own settings/env/account defaults. User-authored `args` win, so there is+ * never a duplicate flag/config override.+ *+ * Returns `provider.args` unchanged (possibly `undefined`) when there is+ * nothing to inject, preserving the prior `args: provider.args` behavior for+ * every other provider type.+ */+export const buildHeteroSpawnArgs = (+ provider: HeterogeneousProviderConfig | undefined | null,+): string[] | undefined => {+ if (!provider) return undefined;+ if (provider.type !== 'claude-code' && provider.type !== 'codex') return provider.args;++ const baseArgs = provider.args ?? [];+ const extraArgs: string[] = [];++ if (provider.type === 'claude-code') {+ const model = getExplicitClaudeCodeModel(provider);+ if (model && !hasCliFlag(baseArgs, '--model')) extraArgs.push('--model', model);+ const effort = getExplicitClaudeCodeReasoningEffort(provider);+ if (effort && !hasCliFlag(baseArgs, '--effort')) extraArgs.push('--effort', effort);+ }++ if (provider.type === 'codex') {+ const model = getExplicitCodexModel(provider);+ if (+ model &&+ !hasAnyCliFlag(baseArgs, CODEX_MODEL_FLAGS) &&+ !hasCliConfigKey(baseArgs, 'model')+ ) {+ extraArgs.push('--model', model);+ }++ const effort = getExplicitCodexReasoningEffort(provider);+ if (effort && !hasCliConfigKey(baseArgs, CODEX_REASONING_EFFORT_CONFIG_KEY)) {+ extraArgs.push('-c', `${CODEX_REASONING_EFFORT_CONFIG_KEY}="${effort}"`);+ }+ }++ if (extraArgs.length === 0) return provider.args;+ return [...baseArgs, ...extraArgs];+};++/**+ * Resolve args for the `lh hetero exec` wrapper.+ *+ * Unlike `buildHeteroSpawnArgs`, these args are consumed by the LobeHub CLI+ * wrapper first, not by the native agent binary. Native provider args are+ * encoded with `--agent-arg=<arg>` so wrapper flags such as `-c, --command`+ * never collide with Codex/Claude flags. Keep selector overrides in the+ * wrapper's `--model` / `--effort` form; `lh hetero exec` translates them into+ * native Codex config immediately before `spawnAgent`.+ */+export const buildHeteroExecArgs = (+ provider: HeterogeneousProviderConfig | undefined | null,+): string[] | undefined => {+ if (!provider) return undefined;+ if (provider.type !== 'claude-code' && provider.type !== 'codex') return provider.args;++ const baseArgs = provider.args ?? [];+ const wrapperArgs = baseArgs.map((arg) => `${HETERO_EXEC_AGENT_ARG_FLAG}=${arg}`);+ const selectorArgs: string[] = [];++ if (provider.type === 'claude-code') {+ const model = getExplicitClaudeCodeModel(provider);+ if (model && !hasCliFlag(baseArgs, '--model')) selectorArgs.push('--model', model);+ const effort = getExplicitClaudeCodeReasoningEffort(provider);+ if (effort && !hasCliFlag(baseArgs, '--effort')) selectorArgs.push('--effort', effort);+ }++ if (provider.type === 'codex') {+ const model = getExplicitCodexModel(provider);+ if (+ model &&+ !hasAnyCliFlag(baseArgs, CODEX_MODEL_FLAGS) &&+ !hasCliConfigKey(baseArgs, 'model')+ ) {+ selectorArgs.push('--model', model);+ }++ const effort = getExplicitCodexReasoningEffort(provider);+ if (+ effort &&+ !hasCliFlag(baseArgs, '--effort') &&+ !hasCliConfigKey(baseArgs, CODEX_REASONING_EFFORT_CONFIG_KEY)+ ) {+ selectorArgs.push('--effort', effort);+ }+ }++ const args = [...wrapperArgs, ...selectorArgs];+ return args.length > 0 ? args : undefined;+};+/*** Where an agent runs.* - `none` : no execution environment — plain chat, no built-in run toolsdiff --git a/src/features/ChatInput/ControlBar/HeteroModel.tsx b/src/features/ChatInput/ControlBar/HeteroModel.tsxnew file mode 100644index 00000000000..e9174a9d693--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroModel.tsx@@ -0,0 +1,507 @@+'use client';++import type {+ ClaudeCodeReasoningEffort,+ CodexReasoningEffort,+ HeterogeneousAgentDefaultSelection,+ HeterogeneousProviderConfig,+} from '@lobechat/types';+import {+ CLAUDE_CODE_REASONING_EFFORT_LEVELS,+ CODEX_REASONING_EFFORT_CONFIG_KEY,+ CODEX_REASONING_EFFORT_LEVELS,+ HETEROGENEOUS_AGENT_DEFAULT_SELECTION,+ resolveClaudeCodeModel,+ resolveClaudeCodeReasoningEffort,+ resolveCodexModel,+ resolveCodexReasoningEffort,+} from '@lobechat/types';+import { Icon } from '@lobehub/ui';+import {+ DropdownMenuItem,+ DropdownMenuPopup,+ DropdownMenuPortal,+ DropdownMenuPositioner,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuSubmenuRoot,+ DropdownMenuSubmenuTrigger,+ DropdownMenuTrigger,+ Tooltip,+} from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import isEqual from 'fast-deep-equal';+import { CheckIcon, ChevronDownIcon, ChevronRightIcon } from 'lucide-react';+import { memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { usePermission } from '@/hooks/usePermission';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';++import { useAgentId } from '../hooks/useAgentId';++type HeteroReasoningEffort =+ | ClaudeCodeReasoningEffort+ | CodexReasoningEffort+ | HeterogeneousAgentDefaultSelection;++type SelectableHeteroProviderType = 'claude-code' | 'codex';++const CLAUDE_CODE_MODEL_OPTIONS = [+ { label: 'Opus 4.8', value: 'opus' },+ { label: 'Sonnet 4.6', value: 'sonnet' },+ { label: 'Haiku 4.5', value: 'haiku' },+] as const;++const CODEX_MODEL_OPTIONS = [+ { label: 'GPT-5.5', value: 'gpt-5.5' },+ { label: 'GPT-5.4', value: 'gpt-5.4' },+ { label: 'GPT-5.4 Mini', value: 'gpt-5.4-mini' },+ { label: 'GPT-5.3 Codex Spark', value: 'gpt-5.3-codex-spark' },+] as const;++const MODEL_LABELS: Record<string, string> = Object.fromEntries(+ [...CLAUDE_CODE_MODEL_OPTIONS, ...CODEX_MODEL_OPTIONS].map((option) => [+ option.value,+ option.label,+ ]),+);++const EFFORT_LABEL_KEYS = {+ [HETEROGENEOUS_AGENT_DEFAULT_SELECTION]: 'heteroAgent.modelSelector.default',+ high: 'heteroAgent.modelSelector.reasoning.high',+ low: 'heteroAgent.modelSelector.reasoning.low',+ max: 'heteroAgent.modelSelector.reasoning.max',+ medium: 'heteroAgent.modelSelector.reasoning.medium',+ xhigh: 'heteroAgent.modelSelector.reasoning.xhigh',+} as const satisfies Record<HeteroReasoningEffort, string>;++const styles = createStaticStyles(({ css }) => ({+ check: css`+ flex: none;+ color: ${cssVar.colorTextSecondary};+ `,+ divider: css`+ height: 1px;+ margin-block: 6px;+ background: ${cssVar.colorSplit};+ `,+ label: css`+ overflow: hidden;+ max-width: 150px;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ option: css`+ cursor: pointer;++ display: flex;+ gap: 18px;+ align-items: center;+ justify-content: space-between;++ min-height: 34px;+ padding-inline: 10px;+ border-radius: 8px;++ font-size: 14px;+ line-height: 1.2;+ color: ${cssVar.colorText};++ transition: background-color 0.2s;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ optionLabel: css`+ overflow: hidden;+ flex: 1;++ min-width: 0;++ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ popup: css`+ padding: 8px;+ border-radius: 16px;+ background: ${cssVar.colorBgElevated};+ box-shadow:+ 0 0 0 1px ${cssVar.colorBorderSecondary},+ 0 12px 32px rgb(0 0 0 / 10%),+ 0 4px 12px rgb(0 0 0 / 8%);+ `,+ scroll: css`+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ max-height: 250px;+ `,+ sectionTitle: css`+ padding-block: 0 8px;+ padding-inline: 10px;++ font-size: 13px;+ line-height: 1.2;+ color: ${cssVar.colorTextQuaternary};+ `,+ submenuTrigger: css`+ display: flex;+ gap: 8px;+ align-items: center;+ justify-content: space-between;++ min-height: 34px;+ padding-inline: 10px;+ border-radius: 8px;++ font-size: 14px;+ color: ${cssVar.colorText};+ `,+ submenuMeta: css`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ submenuTrail: css`+ display: inline-flex;+ flex: none;+ align-items: center;+ justify-content: center;++ color: ${cssVar.colorTextSecondary};+ `,+ trigger: css`+ cursor: pointer;++ display: flex;+ flex: none;+ gap: 6px;+ align-items: center;++ height: 28px;+ padding-inline: 8px;+ border-radius: 6px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ white-space: nowrap;++ transition: all 0.2s;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }+ `,+ triggerDisabled: css`+ cursor: not-allowed;+ opacity: 0.5;++ &:hover {+ color: ${cssVar.colorTextSecondary};+ background: transparent;+ }+ `,+}));++const stripCliFlags = (+ args: string[] | undefined,+ flags: readonly string[],+): string[] | undefined => {+ if (!args) return undefined;++ const next: string[] = [];+ for (let index = 0; index < args.length; index += 1) {+ const arg = args[index];+ if (flags.includes(arg)) {+ const value = args[index + 1];+ if (value && !value.startsWith('-')) index += 1;+ continue;+ }+ if (flags.some((flag) => arg.startsWith(`${flag}=`))) continue;++ next.push(arg);+ }++ return next;+};++const parseCliConfigKey = (assignment: string): string | undefined => {+ const match = assignment.match(/^\s*([\w.-]+)\s*=/);+ return match?.[1];+};++const stripCodexConfigKey = (args: string[] | undefined, key: string): string[] | undefined => {+ if (!args) return undefined;++ const next: string[] = [];+ for (let index = 0; index < args.length; index += 1) {+ const arg = args[index];++ if (arg === '-c' || arg === '--config') {+ const value = args[index + 1];+ if (value && parseCliConfigKey(value) === key) {+ index += 1;+ continue;+ }++ next.push(arg);+ continue;+ }++ if (arg.startsWith('-c=') || arg.startsWith('--config=')) {+ const value = arg.slice(arg.indexOf('=') + 1);+ if (parseCliConfigKey(value) === key) continue;+ }++ next.push(arg);+ }++ return next;+};++const isSelectableProviderType = (+ type: HeterogeneousProviderConfig['type'] | undefined,+): type is SelectableHeteroProviderType => type === 'claude-code' || type === 'codex';++const getModelLabel = (model: string, defaultLabel: string) => {+ if (model === HETEROGENEOUS_AGENT_DEFAULT_SELECTION) return defaultLabel;++ const aliasLabel = MODEL_LABELS[model];+ if (aliasLabel) return aliasLabel;++ const match = /^claude-(opus|sonnet|haiku)-(\d+)-(\d+)/.exec(model);+ if (!match) return model;++ const [, family, major, minor] = match;+ return `${family[0].toUpperCase()}${family.slice(1)} ${major}.${minor}`;+};++const getTriggerText = ({+ defaultConfigLabel,+ defaultModelLabel,+ defaultReasoningLabel,+ effort,+ effortLabel,+ model,+ modelLabel,+}: {+ defaultConfigLabel: string;+ defaultModelLabel: string;+ defaultReasoningLabel: string;+ effort: HeteroReasoningEffort;+ effortLabel: string;+ model: string;+ modelLabel: string;+}) => {+ const isDefaultModel = model === HETEROGENEOUS_AGENT_DEFAULT_SELECTION;+ const isDefaultEffort = effort === HETEROGENEOUS_AGENT_DEFAULT_SELECTION;++ if (isDefaultModel && isDefaultEffort) return defaultConfigLabel;+ if (isDefaultModel) return `${defaultModelLabel} · ${effortLabel}`;+ if (isDefaultEffort) return `${modelLabel} · ${defaultReasoningLabel}`;++ return `${modelLabel} · ${effortLabel}`;+};++const HeteroModel = memo(() => {+ const { t } = useTranslation('chat');+ const agentId = useAgentId();+ const provider = useAgentStore(+ (s) => agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider,+ isEqual,+ );+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);+ const { allowed: canCreateContent, reason } = usePermission('create_content');+ const [open, setOpen] = useState(false);+ const [modelOpen, setModelOpen] = useState(false);++ const patchProvider = useCallback(+ async (patch: Partial<Pick<HeterogeneousProviderConfig, 'effort' | 'model'>>) => {+ if (!canCreateContent || !agentId) return;++ const nextPatch: Partial<HeterogeneousProviderConfig> = { ...patch };+ const providerType = provider?.type;++ if (providerType === 'codex') {+ if ('model' in patch) {+ const args = stripCliFlags(provider?.args, ['--model', '-m']);+ nextPatch.args = stripCodexConfigKey(args, 'model');+ }+ if ('effort' in patch) {+ const sourceArgs = nextPatch.args ?? provider?.args;+ nextPatch.args = stripCodexConfigKey(sourceArgs, CODEX_REASONING_EFFORT_CONFIG_KEY);+ }+ } else {+ if ('model' in patch) {+ nextPatch.args = stripCliFlags(provider?.args, ['--model']);+ }+ if ('effort' in patch) {+ const sourceArgs = nextPatch.args ?? provider?.args;+ nextPatch.args = stripCliFlags(sourceArgs, ['--effort']);+ }+ }++ await updateAgentConfigById(agentId, {+ agencyConfig: { heterogeneousProvider: nextPatch },+ });+ },+ [agentId, canCreateContent, provider?.args, provider?.type, updateAgentConfigById],+ );+ const closeMenu = useCallback(() => {+ setOpen(false);+ setModelOpen(false);+ }, []);+ const handleOpenChange = useCallback((value: boolean) => {+ setOpen(value);+ if (!value) setModelOpen(false);+ }, []);+ const selectModel = useCallback(+ (value: string) => {+ closeMenu();+ void patchProvider({ model: value });+ },+ [closeMenu, patchProvider],+ );+ const selectReasoningEffort = useCallback(+ (value: HeteroReasoningEffort) => {+ closeMenu();+ void patchProvider({ effort: value });+ },+ [closeMenu, patchProvider],+ );++ if (!isSelectableProviderType(provider?.type)) return null;++ const providerType = provider.type;+ const model =+ providerType === 'codex' ? resolveCodexModel(provider) : resolveClaudeCodeModel(provider);+ const effort =+ providerType === 'codex'+ ? resolveCodexReasoningEffort(provider)+ : resolveClaudeCodeReasoningEffort(provider);+ const defaultLabel = t('heteroAgent.modelSelector.default');+ const modelLabel = getModelLabel(model, defaultLabel);+ const effortLabel = t(EFFORT_LABEL_KEYS[effort]);+ const reasoningLevels =+ providerType === 'codex' ? CODEX_REASONING_EFFORT_LEVELS : CLAUDE_CODE_REASONING_EFFORT_LEVELS;+ const providerModelOptions =+ providerType === 'codex' ? CODEX_MODEL_OPTIONS : CLAUDE_CODE_MODEL_OPTIONS;+ const effortOptions: { label: string; value: HeteroReasoningEffort }[] = [+ { label: defaultLabel, value: HETEROGENEOUS_AGENT_DEFAULT_SELECTION },+ ...reasoningLevels.map((level) => ({+ label: t(EFFORT_LABEL_KEYS[level]),+ value: level,+ })),+ ];+ const baseModelOptions: { label: string; value: string }[] = [+ { label: defaultLabel, value: HETEROGENEOUS_AGENT_DEFAULT_SELECTION },+ ...providerModelOptions,+ ];+ const modelOptions = baseModelOptions.some((option) => option.value === model)+ ? baseModelOptions+ : [{ label: model, value: model }, ...baseModelOptions];+ const triggerText = getTriggerText({+ defaultConfigLabel: t('heteroAgent.modelSelector.defaultConfig'),+ defaultModelLabel: t('heteroAgent.modelSelector.defaultModel'),+ defaultReasoningLabel: t('heteroAgent.modelSelector.defaultReasoning'),+ effort,+ effortLabel,+ model,+ modelLabel,+ });++ const trigger = (+ <div+ className={cx(styles.trigger, !canCreateContent && styles.triggerDisabled)}+ aria-label={t('heteroAgent.modelSelector.ariaLabel', {+ model: modelLabel,+ reasoning: effortLabel,+ })}+ >+ <span className={styles.label}>{triggerText}</span>+ <Icon icon={ChevronDownIcon} size={12} />+ </div>+ );++ if (!canCreateContent)+ return (+ <Tooltip title={reason}>+ <div>{trigger}</div>+ </Tooltip>+ );++ const renderOption = <T extends string>(+ title: string,+ options: readonly { label: string; value: T }[],+ current: T,+ onSelect: (value: T) => void,+ ) =>+ options.map((option) => (+ <DropdownMenuItem+ className={styles.option}+ data-selected={current === option.value ? 'true' : undefined}+ key={`${title}-${option.value}`}+ onClick={() => void onSelect(option.value)}+ >+ <span className={styles.optionLabel}>{option.label}</span>+ {current === option.value && <Icon className={styles.check} icon={CheckIcon} size={16} />}+ </DropdownMenuItem>+ ));++ return (+ <DropdownMenuRoot open={open} onOpenChange={handleOpenChange}>+ <DropdownMenuTrigger nativeButton={false}>{trigger}</DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuPositioner placement="topRight" sideOffset={8}>+ <DropdownMenuPopup className={styles.popup} style={{ width: 208 }}>+ <div className={styles.sectionTitle}>{t('heteroAgent.modelSelector.reasoning')}</div>+ <div className={styles.scroll}>+ {renderOption('reasoning', effortOptions, effort, selectReasoningEffort)}+ </div>+ <DropdownMenuSeparator className={styles.divider} />+ <DropdownMenuSubmenuRoot open={modelOpen} onOpenChange={setModelOpen}>+ <DropdownMenuSubmenuTrigger+ className={styles.submenuTrigger}+ onMouseEnter={() => setModelOpen(true)}+ onClick={(event) => {+ event.preventDefault();+ setModelOpen(true);+ }}+ >+ <span className={styles.submenuMeta}>{modelLabel}</span>+ <span className={styles.submenuTrail}>+ <Icon icon={ChevronRightIcon} size={16} />+ </span>+ </DropdownMenuSubmenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuPositioner+ alignOffset={-4}+ anchor={null}+ placement="right"+ sideOffset={8}+ >+ <DropdownMenuPopup className={styles.popup} style={{ minWidth: 200 }}>+ <div className={styles.sectionTitle}>+ {t('heteroAgent.modelSelector.model')}+ </div>+ <div className={styles.scroll}>+ {renderOption('model', modelOptions, model, selectModel)}+ </div>+ </DropdownMenuPopup>+ </DropdownMenuPositioner>+ </DropdownMenuPortal>+ </DropdownMenuSubmenuRoot>+ </DropdownMenuPopup>+ </DropdownMenuPositioner>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ );+});++HeteroModel.displayName = 'HeteroModel';++export default HeteroModel;diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsxindex 8d45a3050a2..de4121a9389 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx@@ -7,11 +7,14 @@ import { CircleAlertIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import HeteroModel from '@/features/ChatInput/ControlBar/HeteroModel';import WorkspaceControls from '@/features/ChatInput/ControlBar/WorkspaceControls';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';+import { shouldShowHeteroModelSelector } from './shouldShowHeteroModelSelector';+const styles = createStaticStyles(({ css }) => ({bar: css`container: runtimebar / inline-size;@@ -54,6 +57,9 @@ const styles = createStaticStyles(({ css }) => ({display: none;}`,+ rightGroup: css`+ flex: none;+ `,}));const HeteroControlBar = memo(() => {@@ -62,6 +68,12 @@ const HeteroControlBar = memo(() => {// All hooks must be called unconditionally (Rules of Hooks)const isLoading = useAgentStore(agentByIdSelectors.isAgentConfigLoadingById(agentId));+ const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));+ const showModelSelector = shouldShowHeteroModelSelector({+ boundDeviceId: agencyConfig?.boundDeviceId,+ executionTarget: agencyConfig?.executionTarget,+ isDesktopClient: isDesktop,+ });// On web there's no full-access badge / skeleton — just the workspace controls// (the cloud repo switcher is rendered inside WorkspaceControls).@@ -72,6 +84,9 @@ const HeteroControlBar = memo(() => {<Flexbox horizontal align={'center'} className={styles.leftGroup} gap={4}><WorkspaceControls alwaysShowWorkspace agentId={agentId} /></Flexbox>+ <Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>+ {showModelSelector && <HeteroModel />}+ </Flexbox></Flexbox>);}@@ -97,7 +112,10 @@ const HeteroControlBar = memo(() => {<Flexbox horizontal align={'center'} className={styles.leftGroup} gap={4}><WorkspaceControls alwaysShowWorkspace agentId={agentId} /></Flexbox>- <Tooltip title={tChat('heteroAgent.fullAccess.tooltip')}>{fullAccessBadge}</Tooltip>+ <Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>+ {showModelSelector && <HeteroModel />}+ <Tooltip title={tChat('heteroAgent.fullAccess.tooltip')}>{fullAccessBadge}</Tooltip>+ </Flexbox></Flexbox>);});diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsxindex ee5bf2ad8fb..baf8ae9a460 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx@@ -24,11 +24,11 @@ import { useChatStore } from '@/store/chat';import HeteroControlBar from './HeteroControlBar';-// Heterogeneous agents (e.g. Claude Code) bring their own toolchain, memory,-// and model, so LobeHub-side pickers don't apply. Typo is kept so the user-// can still toggle the rich-text formatting bar.+// Heterogeneous agents (e.g. Claude Code) bring their own toolchain and memory,+// so most LobeHub-side pickers don't apply. Typo is kept so the user can still+// toggle the rich-text formatting bar. Local CLI model + thinking effort live+// in the control bar next to workspace controls, not beside the send button.const leftActions: ActionKeys[] = ['typo'];-const rightActions: ActionKeys[] = [];/*** GuardBanner@@ -175,7 +175,6 @@ const HeterogeneousChatInput = memo(() => {<ChatInputcontrolBarSlot={<HeteroControlBar />}leftActions={leftActions}- rightActions={rightActions}sendButtonProps={{ disabled: inputDisabled, shape: 'round' }}skipScrollMarginWithList={!hasGuard}onEditorReady={(instance) => {diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.tsnew file mode 100644index 00000000000..5b0e955eb9d--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';++import { shouldShowHeteroModelSelector } from './shouldShowHeteroModelSelector';++describe('shouldShowHeteroModelSelector', () => {+ it('shows for sandbox-backed web runs', () => {+ expect(+ shouldShowHeteroModelSelector({+ executionTarget: 'sandbox',+ isDesktopClient: false,+ }),+ ).toBe(true);+ });++ it('shows for desktop-local runs even when the desktop device id is persisted', () => {+ expect(+ shouldShowHeteroModelSelector({+ boundDeviceId: 'desktop-device',+ executionTarget: 'local',+ isDesktopClient: true,+ }),+ ).toBe(true);+ });++ it('hides for explicit device runs because connected devices do not advertise selector args yet', () => {+ expect(+ shouldShowHeteroModelSelector({+ boundDeviceId: 'remote-device',+ executionTarget: 'device',+ isDesktopClient: false,+ }),+ ).toBe(false);+ });++ it('hides for desktop-local selections opened from web because they dispatch to the bound device', () => {+ expect(+ shouldShowHeteroModelSelector({+ boundDeviceId: 'desktop-device',+ executionTarget: 'local',+ isDesktopClient: false,+ }),+ ).toBe(false);+ });++ it('hides for auto device routing because selector args are not forwarded there', () => {+ expect(+ shouldShowHeteroModelSelector({+ executionTarget: 'auto',+ isDesktopClient: false,+ }),+ ).toBe(false);+ });+});diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.tsnew file mode 100644index 00000000000..76e720eb0ed--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts@@ -0,0 +1,22 @@+import type { DeviceExecutionTarget } from '@lobechat/types';++interface ShouldShowHeteroModelSelectorParams {+ boundDeviceId?: string;+ executionTarget?: DeviceExecutionTarget;+ isDesktopClient: boolean;+}++export const shouldShowHeteroModelSelector = ({+ boundDeviceId,+ executionTarget,+ isDesktopClient,+}: ShouldShowHeteroModelSelectorParams): boolean => {+ if (executionTarget === 'auto' || executionTarget === 'device') return false;++ // A desktop "local" selection stores that desktop's connected-device id so+ // web clients can route back to the same machine. On web this is a device+ // dispatch, and selector args are not capability-gated for devices yet.+ if (!isDesktopClient && executionTarget === 'local' && boundDeviceId) return false;++ return true;+};diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 419b2019d7e..b81de172064 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -1225,6 +1225,80 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(mockSendPrompt).toHaveBeenCalledWith('ipc-sess-1', 'test prompt', 'op-1', imageList);});+ it('should pass Claude Code model and thinking effort as spawn args', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);++ await executeHeterogeneousAgent(get, {+ ...defaultParams,+ heterogeneousProvider: {+ args: ['--verbose'],+ command: 'claude',+ effort: 'high',+ model: 'opus',+ type: 'claude-code' as const,+ },+ });++ expect(mockStartSession).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--verbose', '--model', 'opus', '--effort', 'high'],+ agentType: 'claude-code',+ }),+ );+ });++ it('should pass Codex model and thinking effort as spawn args', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);++ await executeHeterogeneousAgent(get, {+ ...defaultParams,+ heterogeneousProvider: {+ args: ['--ask-for-approval', 'never'],+ command: 'codex',+ effort: 'xhigh',+ model: 'gpt-5.5',+ type: 'codex' as const,+ },+ });++ expect(mockStartSession).toHaveBeenCalledWith(+ expect.objectContaining({+ agentType: 'codex',+ args: [+ '--ask-for-approval',+ 'never',+ '--model',+ 'gpt-5.5',+ '-c',+ 'model_reasoning_effort="xhigh"',+ ],+ }),+ );+ });++ it('should preserve Claude Code defaults when model and effort are not selected', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);++ await executeHeterogeneousAgent(get, {+ ...defaultParams,+ heterogeneousProvider: {+ args: ['--verbose'],+ command: 'claude',+ type: 'claude-code' as const,+ },+ });++ expect(mockStartSession).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--verbose'],+ agentType: 'claude-code',+ }),+ );+ });+it('should clear stale resume metadata and retry once without resume for recoverable Codex errors', async () => {const store = createMockStore();const get = vi.fn(() => store);diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex dbcc5f28bee..5a5840fb380 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -26,7 +26,12 @@ import type {MessageMapScope,UIChatMessage,} from '@lobechat/types';-import { AgentRuntimeErrorType, ThreadStatus, ThreadType } from '@lobechat/types';+import {+ AgentRuntimeErrorType,+ buildHeteroSpawnArgs,+ ThreadStatus,+ ThreadType,+} from '@lobechat/types';import { createNanoId } from '@lobechat/utils';import { t } from 'i18next';@@ -1056,7 +1061,7 @@ export const executeHeterogeneousAgent = async (// Start session (pass resumeSessionId for multi-turn --resume)const result = await heterogeneousAgentService.startSession({agentType: adapterType,- args: heterogeneousProvider.args,+ args: buildHeteroSpawnArgs(heterogeneousProvider),command: heterogeneousProvider.command || (adapterType === 'codex' ? 'codex' : 'claude'),cwd: workingDirectory,env: heterogeneousProvider.env,