Skip to content

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

✨ feat(claude-code): add local API provider mode (#18468)

AmAzing-9a22d1685fe4
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 5633808e4c2..dbaece47994 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -404,6 +404,32 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
);
});
+ it('should reject Claude Code API mode before sandbox or device dispatch', async () => {
+ heteroAgentConfig.agencyConfig = {
+ executionTarget: 'sandbox',
+ heterogeneousProvider: {
+ apiConfig: { model: 'claude-test', providerId: 'anthropic' },
+ authMode: 'api',
+ type: 'claude-code',
+ },
+ } as any;
+
+ const result = await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'This must not receive provider credentials remotely',
+ });
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ error: expect.stringContaining('Desktop local execution'),
+ status: 'error',
+ success: false,
+ }),
+ );
+ expect(mockSpawnHeteroSandbox).not.toHaveBeenCalled();
+ expect(mockDispatchAgentRun).not.toHaveBeenCalled();
+ });
+
it('should pass resolved Codex model and reasoning effort args to sandbox dispatch', async () => {
heteroAgentConfig.model = 'codex';
heteroAgentConfig.provider = 'codex';
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 80b97842742..2b840d53d40 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -48,6 +48,7 @@ import {
import type { LobeChatDatabase } from '@lobechat/database';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import {
+ CLAUDE_CODE_API_LOCAL_ONLY_ERROR,
getHeterogeneousAgentConfig,
isLocalHeterogeneousType,
isRemoteHeterogeneousType,
@@ -2486,6 +2487,34 @@ export class AiAgentService {
},
});
+ if (
+ agentConfig.agencyConfig?.heterogeneousProvider?.type === 'claude-code' &&
+ agentConfig.agencyConfig.heterogeneousProvider.authMode === 'api'
+ ) {
+ await this.finalizeHeteroDispatchError({
+ agentId: resolvedAgentId,
+ assistantMessageId: assistantMessageRecord.id,
+ detail: CLAUDE_CODE_API_LOCAL_ONLY_ERROR,
+ message: 'Claude Code API mode does not support this execution target',
+ operationId,
+ topicId,
+ });
+ return {
+ agentId: resolvedAgentId,
+ assistantMessageId: assistantMessageRecord.id,
+ autoStarted: false,
+ createdAt: new Date().toISOString(),
+ error: CLAUDE_CODE_API_LOCAL_ONLY_ERROR,
+ message: 'Claude Code API mode requires Desktop local execution',
+ operationId,
+ status: 'error',
+ success: false,
+ timestamp: new Date().toISOString(),
+ topicId,
+ userMessageId: userMessageRecord?.id ?? parentMessageId ?? '',
+ };
+ }
+
// Notify-based platform agents (openclaw / hermes) communicate back via
// agentNotify.notify. A local run uses the requesting desktop's device ID;
// a remote run uses agencyConfig.boundDeviceId. Both use the gateway transport,
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 4bbee45f119..060946f9892 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -528,6 +528,14 @@
"groupWizard.searchTemplates": "Search templates...",
"groupWizard.title": "Create Group",
"groupWizard.useTemplate": "Use Template",
+ "heteroAgent.apiMode.configMissing": "Claude Code API mode requires a provider and model binding. Open the agent profile to configure it.",
+ "heteroAgent.apiMode.labDisabled.action": "Enable in Labs",
+ "heteroAgent.apiMode.labDisabled.desc": "Turn it on in Settings → Labs, or switch this agent to Subscription authentication.",
+ "heteroAgent.apiMode.labDisabled.title": "Claude Code API mode is a Labs experiment",
+ "heteroAgent.apiMode.localOnly.desc": "Switch the execution environment to Local device, or use Subscription authentication.",
+ "heteroAgent.apiMode.localOnly.title": "API mode requires Desktop local execution",
+ "heteroAgent.apiMode.modelUnavailable": "The model \"{{providerId}}/{{model}}\" is disabled or no longer available.",
+ "heteroAgent.apiMode.providerUnavailable": "The provider \"{{providerId}}\" is disabled or no longer available.",
"heteroAgent.claudeQuota.accountActive": "In use",
"heteroAgent.claudeQuota.accountSwitch": "Switch",
"heteroAgent.claudeQuota.accounts": "Accounts",
diff --git a/locales/en-US/labs.json b/locales/en-US/labs.json
index 6c9954a45cf..646eaf0174f 100644
--- a/locales/en-US/labs.json
+++ b/locales/en-US/labs.json
@@ -8,6 +8,8 @@
"features.artifactDeployment.title": "Artifact Deployments",
"features.assistantMessageGroup.desc": "Group agent messages and their tool call results together for display",
"features.assistantMessageGroup.title": "Agent Message Grouping",
+ "features.claudeCodeApiMode.desc": "Let Claude Code use a configured API provider and model on this desktop instead of a Claude subscription. Desktop local execution only.",
+ "features.claudeCodeApiMode.title": "Claude Code API Provider",
"features.claudeCodeSdk.desc": "Run Claude Code sessions through the Claude Agent SDK instead of spawning the CLI. Enables richer streaming and session control.",
"features.claudeCodeSdk.title": "Claude Code SDK Runtime",
"features.codexAppServer.desc": "Run Codex sessions through the local app-server instead of one-shot CLI processes. Enables token streaming and native turn control.",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 622dc56f120..a3a73035b1f 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -449,6 +449,16 @@
"header.sessionWithName": "Agent Settings · {{name}}",
"header.title": "Settings",
"heterogeneousStatus.account.label": "Account",
+ "heterogeneousStatus.apiMode.configureProvider": "Go to provider settings",
+ "heterogeneousStatus.apiMode.enableInLabs": "Enable in Labs",
+ "heterogeneousStatus.apiMode.labDisabled": "API authentication is a Labs experiment. Enable it to use a configured provider instead of a Claude subscription.",
+ "heterogeneousStatus.apiMode.localOnly": "Available only for Desktop local execution",
+ "heterogeneousStatus.apiMode.model": "Model",
+ "heterogeneousStatus.apiMode.modelPlaceholder": "Select a model",
+ "heterogeneousStatus.apiMode.noProviders": "No enabled provider with an Anthropic-compatible endpoint is configured.",
+ "heterogeneousStatus.apiMode.smallFastModel": "Background model",
+ "heterogeneousStatus.apiMode.smallFastModelDesc": "Used for session titles, summaries, and other background work. Does not change the main conversation.",
+ "heterogeneousStatus.apiMode.smallFastModelPlaceholder": "Same as primary model",
"heterogeneousStatus.auth.api": "API",
"heterogeneousStatus.auth.label": "Auth Method",
"heterogeneousStatus.auth.subscription": "Subscription",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 37063c01745..64156bd03a1 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -528,6 +528,14 @@
"groupWizard.searchTemplates": "搜索模板…",
"groupWizard.title": "创建群组",
"groupWizard.useTemplate": "使用模板",
+ "heteroAgent.apiMode.configMissing": "Claude Code API 模式需要绑定服务商和模型,请先前往 Agent 资料完成配置。",
+ "heteroAgent.apiMode.labDisabled.action": "前往实验室开启",
+ "heteroAgent.apiMode.labDisabled.desc": "请在「设置 → 实验室」中打开,或将此 Agent 改回订阅认证。",
+ "heteroAgent.apiMode.labDisabled.title": "Claude Code API 模式是实验室功能",
+ "heteroAgent.apiMode.localOnly.desc": "请将执行环境切换为本地设备,或改用订阅认证。",
+ "heteroAgent.apiMode.localOnly.title": "API 模式仅支持桌面端本地执行",
+ "heteroAgent.apiMode.modelUnavailable": "模型「{{providerId}}/{{model}}」已禁用或不再可用。",
+ "heteroAgent.apiMode.providerUnavailable": "服务商「{{providerId}}」已禁用或不再可用。",
"heteroAgent.claudeQuota.accountActive": "使用中",
"heteroAgent.claudeQuota.accountSwitch": "切换",
"heteroAgent.claudeQuota.accounts": "账号",
diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.json
index 68f4d277be6..5102ed80d14 100644
--- a/locales/zh-CN/labs.json
+++ b/locales/zh-CN/labs.json
@@ -8,6 +8,8 @@
"features.artifactDeployment.title": "Artifact 部署",
"features.assistantMessageGroup.desc": "将代理消息及其工具调用结果组合在一起显示",
"features.assistantMessageGroup.title": "代理消息分组",
+ "features.claudeCodeApiMode.desc": "让 Claude Code 在本机使用已配置的 API 服务商和模型,而不是 Claude 订阅。仅支持桌面端本地执行。",
+ "features.claudeCodeApiMode.title": "Claude Code API 服务商",
"features.claudeCodeSdk.desc": "通过 Claude Agent SDK 运行 Claude Code 会话,替代 CLI 进程方式,提供更丰富的流式输出与会话控制。",
"features.claudeCodeSdk.title": "Claude Code SDK 运行时",
"features.codexAppServer.desc": "通过本地 App Server 运行 Codex 会话,替代一次性的 CLI 进程,提供 Token 流式输出与原生 Turn 控制。",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 283be0374c9..87b872554e7 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -449,6 +449,16 @@
"header.sessionWithName": "会话设置 · {{name}}",
"header.title": "设置",
"heterogeneousStatus.account.label": "账号",
+ "heterogeneousStatus.apiMode.configureProvider": "前往服务商设置",
+ "heterogeneousStatus.apiMode.enableInLabs": "前往实验室开启",
+ "heterogeneousStatus.apiMode.labDisabled": "API 认证是实验室功能。开启后即可使用已配置的服务商,而不是 Claude 订阅。",
+ "heterogeneousStatus.apiMode.localOnly": "仅支持桌面端本地执行",
+ "heterogeneousStatus.apiMode.model": "模型",
+ "heterogeneousStatus.apiMode.modelPlaceholder": "选择模型",
+ "heterogeneousStatus.apiMode.noProviders": "尚未配置已启用且兼容 Anthropic 接口的服务商。",
+ "heterogeneousStatus.apiMode.smallFastModel": "后台模型",
+ "heterogeneousStatus.apiMode.smallFastModelDesc": "Claude Code 用来生成会话标题、摘要等后台任务,不影响主对话。",
+ "heterogeneousStatus.apiMode.smallFastModelPlaceholder": "不设置则与主模型相同",
"heterogeneousStatus.auth.api": "API",
"heterogeneousStatus.auth.label": "认证方式",
"heterogeneousStatus.auth.subscription": "订阅",
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index e7807e26350..3f8b298088e 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -1213,6 +1213,44 @@ describe('AgentModel', () => {
expect(result?.updatedAt.getTime()).toBeGreaterThan(originalUpdatedAt.getTime());
});
+ it('should persist only reference fields in an API binding and clear fast model with null', async () => {
+ const agent = await agentModel.create({
+ agencyConfig: {
+ heterogeneousProvider: {
+ apiConfig: {
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ smallFastModel: 'claude-fast',
+ },
+ authMode: 'api',
+ type: 'claude-code',
+ },
+ },
+ });
+
+ await agentModel.updateConfig(agent.id, {
+ agencyConfig: {
+ heterogeneousProvider: {
+ apiConfig: {
+ apiKey: 'must-not-persist',
+ keyVaults: { apiKey: 'must-not-persist' },
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ smallFastModel: null,
+ },
+ },
+ },
+ } as any);
+
+ const result = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+
+ expect(result?.agencyConfig?.heterogeneousProvider?.apiConfig).toEqual({
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ smallFastModel: null,
+ });
+ });
+
it('should update updatedAt even when only updating meta fields like avatar', async () => {
const agent = await serverDB
.insert(agents)
@@ -1393,6 +1431,28 @@ describe('AgentModel', () => {
});
describe('create', () => {
+ it('should strip secrets and unknown fields from an API binding', async () => {
+ const agent = await agentModel.create({
+ agencyConfig: {
+ heterogeneousProvider: {
+ apiConfig: {
+ apiKey: 'must-not-persist',
+ keyVaults: { apiKey: 'must-not-persist' },
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ },
+ authMode: 'api',
+ type: 'claude-code',
+ },
+ },
+ } as any);
+
+ expect(agent.agencyConfig?.heterogeneousProvider?.apiConfig).toEqual({
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ });
+ });
+
it('should persist explicit selection policy defaults only for workspace agents', async () => {
const [workspace] = await serverDB
.insert(workspaces)
@@ -1427,6 +1487,30 @@ describe('AgentModel', () => {
expect(agent.slug).toBe('my-own-slug');
});
+ it('should also strip API binding secrets from direct updates', async () => {
+ const agent = await agentModel.create({ title: 'API Agent' });
+
+ await agentModel.update(agent.id, {
+ agencyConfig: {
+ heterogeneousProvider: {
+ apiConfig: {
+ apiKey: 'must-not-persist',
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ },
+ authMode: 'api',
+ type: 'claude-code',
+ },
+ },
+ } as any);
+
+ const result = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(result?.agencyConfig?.heterogeneousProvider?.apiConfig).toEqual({
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ });
+ });
+
// Identity / scope / provisioning fields feed authorization, so no update may
// carry them — otherwise the edit access granted on a collaborative builtin
// could declassify, orphan or rehome it.
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 788c4efa806..74fe38aad00 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -76,6 +76,7 @@ import { rehomeAgentQuotaBindingsForRecipient } from '../utils/agentQuotaBinding
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
import { resolveGroupMembershipType } from '../utils/groupMembership';
import { normalizeInboxAgentMeta } from '../utils/inboxAgent';
+import { sanitizeAgentApiConfig } from '../utils/sanitizeAgentApiConfig';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from './agentCopyJob';
import {
@@ -1038,7 +1039,9 @@ export class AgentModel {
*/
create = async (input: Partial<AgentItem>): Promise<AgentItem> => {
const config = this.stripReservedSlug(input);
- const agencyConfig = this.withWorkspaceSelectionPolicyDefaults(config.agencyConfig);
+ const agencyConfig = this.withWorkspaceSelectionPolicyDefaults(
+ sanitizeAgentApiConfig(config.agencyConfig),
+ );
await this.assertWorkspaceDeviceBinding(this.workspaceId ?? null, agencyConfig);
await this.assertFixedExecutionTarget(this.workspaceId ?? null, agencyConfig);
@@ -1069,7 +1072,9 @@ export class AgentModel {
const normalizedConfigs = configs.map((config) => ({
...this.stripReservedSlug(config),
- agencyConfig: this.withWorkspaceSelectionPolicyDefaults(config.agencyConfig),
+ agencyConfig: this.withWorkspaceSelectionPolicyDefaults(
+ sanitizeAgentApiConfig(config.agencyConfig),
+ ),
}));
await Promise.all(
@@ -1096,9 +1101,12 @@ export class AgentModel {
};
update = async (agentId: string, data: Partial<AgentItem>) => {
+ const apiSafeData = Object.hasOwn(data, 'agencyConfig')
+ ? { ...data, agencyConfig: sanitizeAgentApiConfig(data.agencyConfig) }
+ : data;
const sanitizedData = await this.stripAgentBuilderProtectedFields(
agentId,
- this.stripImmutableFields(data),
+ this.stripImmutableFields(apiSafeData),
);
return this.db
@@ -1361,6 +1369,7 @@ export class AgentModel {
}
const mergedValue = merge(agent, restData);
+ mergedValue.agencyConfig = sanitizeAgentApiConfig(mergedValue.agencyConfig) ?? null;
// The inbox is LobeHub's built-in default cloud agent; it must never be
// turned into a heterogeneous (external-CLI) agent. Two independent inputs can
diff --git a/packages/database/src/utils/sanitizeAgentApiConfig.ts b/packages/database/src/utils/sanitizeAgentApiConfig.ts
new file mode 100644
index 00000000000..b6bc789992d
--- /dev/null
+++ b/packages/database/src/utils/sanitizeAgentApiConfig.ts
@@ -0,0 +1,36 @@
+import type { HeterogeneousApiConfig, LobeAgentAgencyConfig } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+
+/** Keep provider credentials and arbitrary client fields out of persisted Agent API bindings. */
+export const sanitizeAgentApiConfig = (
+ agencyConfig: LobeAgentAgencyConfig | null | undefined,
+): LobeAgentAgencyConfig | null | undefined => {
+ const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
+ if (!heterogeneousProvider || !Object.hasOwn(heterogeneousProvider, 'apiConfig')) {
+ return agencyConfig;
+ }
+
+ const rawApiConfig = heterogeneousProvider.apiConfig;
+ let apiConfig: HeterogeneousApiConfig | undefined;
+ if (
+ isRecord(rawApiConfig) &&
+ typeof rawApiConfig.model === 'string' &&
+ typeof rawApiConfig.providerId === 'string'
+ ) {
+ apiConfig = {
+ model: rawApiConfig.model,
+ providerId: rawApiConfig.providerId,
+ ...(typeof rawApiConfig.smallFastModel === 'string' || rawApiConfig.smallFastModel === null
+ ? { smallFastModel: rawApiConfig.smallFastModel }
+ : {}),
+ };
+ }
+
+ return {
+ ...agencyConfig,
+ heterogeneousProvider: {
+ ...heterogeneousProvider,
+ apiConfig,
+ },
+ };
+};
diff --git a/packages/heterogeneous-agents/src/claudeCodeDirectEnv.test.ts b/packages/heterogeneous-agents/src/claudeCodeDirectEnv.test.ts
new file mode 100644
index 00000000000..c4ca9017d13
--- /dev/null
+++ b/packages/heterogeneous-agents/src/claudeCodeDirectEnv.test.ts
@@ -0,0 +1,128 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildClaudeCodeDirectEnv,
+ sanitizeClaudeCodeDirectArgs,
+ sanitizeClaudeCodeDirectEnv,
+} from './claudeCodeDirectEnv';
+
+describe('Claude Code Desktop-local direct binding', () => {
+ it('builds a host-managed Anthropic environment and defaults the fast model to primary', () => {
+ const result = buildClaudeCodeDirectEnv({
+ keyVaults: { apiKey: ' test-key ', baseURL: ' https://example.com/anthropic ' },
+ model: 'claude-sonnet-test',
+ sdkType: 'anthropic',
+ });
+
+ expect(result.error).toBeUndefined();
+ expect(result.env).toEqual({
+ ANTHROPIC_AUTH_TOKEN: 'test-key',
+ ANTHROPIC_BASE_URL: 'https://example.com/anthropic',
+ ANTHROPIC_MODEL: 'claude-sonnet-test',
+ ANTHROPIC_SMALL_FAST_MODEL: 'claude-sonnet-test',
+ CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST: '1',
+ CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: '1',
+ CLAUDE_CODE_USE_BEDROCK: '0',
+ CLAUDE_CODE_USE_MANTLE: '0',
+ CLAUDE_CODE_USE_VERTEX: '0',
+ });
+ });
+
+ it.each([
+ ['https://gateway.example.com/v1/', 'https://gateway.example.com'],
+ ['https://gateway.example.com/v1/messages', 'https://gateway.example.com'],
+ ['https://gateway.example.com/v1/messages/', 'https://gateway.example.com'],
+ [`https://gateway.example.com/v1/messages${'/'.repeat(64)}`, 'https://gateway.example.com'],
+ ['https://gateway.example.com/anthropic', 'https://gateway.example.com/anthropic'],
+ [
+ 'https://gateway.example.com/v1/messages/extra',
+ 'https://gateway.example.com/v1/messages/extra',
+ ],
+ ['https://gateway.example.com/v10', 'https://gateway.example.com/v10'],
+ ])('normalizes Claude Code base URL %s', (baseURL, expected) => {
+ expect(
+ buildClaudeCodeDirectEnv({
+ keyVaults: { apiKey: 'test-key', baseURL },
+ model: 'primary',
+ sdkType: 'anthropic',
+ }).env.ANTHROPIC_BASE_URL,
+ ).toBe(expected);
+ });
+
+ it('drops a slash-only base URL instead of emitting an empty env value', () => {
+ expect(
+ buildClaudeCodeDirectEnv({
+ keyVaults: { apiKey: 'test-key', baseURL: '///' },
+ model: 'primary',
+ sdkType: 'anthropic',
+ }).env.ANTHROPIC_BASE_URL,
+ ).toBeUndefined();
+ });
+
+ it('uses ANTHROPIC_API_KEY for first-party Anthropic and AUTH_TOKEN for custom gateways', () => {
+ expect(
+ buildClaudeCodeDirectEnv({
+ keyVaults: { apiKey: 'official-key' },
+ model: 'primary',
+ sdkType: 'anthropic',
+ }).env,
+ ).toMatchObject({ ANTHROPIC_API_KEY: 'official-key' });
+ expect(
+ buildClaudeCodeDirectEnv({
+ keyVaults: { apiKey: 'gateway-key', baseURL: 'https://useaifor.me' },
+ model: 'primary',
+ sdkType: 'anthropic',
+ }).env,
+ ).toMatchObject({
+ ANTHROPIC_AUTH_TOKEN: 'gateway-key',
+ ANTHROPIC_BASE_URL: 'https://useaifor.me',
+ });
+ });
+
+ it('uses an explicitly bound fast model', () => {
+ const result = buildClaudeCodeDirectEnv({
+ keyVaults: { apiKey: 'test-key' },
+ model: 'primary',
+ sdkType: 'anthropic',
+ smallFastModel: 'fast',
+ });
+
+ expect(result.env.ANTHROPIC_SMALL_FAST_MODEL).toBe('fast');
+ });
+
+ it.each([
+ [{ apiKey: 'key' }, '', 'anthropic', /Model id/],
+ [{}, 'model', 'anthropic', /apiKey/],
+ [{ apiKey: 'key' }, 'model', 'openai', /sdkType/],
+ ])('fails for incomplete or unsupported bindings', (keyVaults, model, sdkType, error) => {
+ expect(buildClaudeCodeDirectEnv({ keyVaults, model, sdkType }).error).toMatch(error);
+ });
+
+ it('removes stale model flags in both supported CLI forms', () => {
+ expect(
+ sanitizeClaudeCodeDirectArgs([
+ '--effort',
+ 'high',
+ '--model',
+ 'subscription-model',
+ '--model=other-model',
+ '--verbose',
+ ]),
+ ).toEqual(['--effort', 'high', '--verbose']);
+ });
+
+ it('removes stale auth, model, and cloud routing env without touching unrelated env', () => {
+ expect(
+ sanitizeClaudeCodeDirectEnv({
+ ANTHROPIC_API_KEY: 'old-key',
+ ANTHROPIC_AUTH_TOKEN: 'old-token',
+ ANTHROPIC_BASE_URL: 'https://old.example.com',
+ ANTHROPIC_MODEL: 'old-model',
+ CLAUDE_CODE_USE_BEDROCK: '1',
+ CLAUDE_CODE_USE_MANTLE: '1',
+ CLAUDE_CODE_USE_VERTEX: '1',
+ KEEP_ME: 'yes',
+ }),
+ ).toEqual({ KEEP_ME: 'yes' });
+ });
+});
diff --git a/packages/heterogeneous-agents/src/claudeCodeDirectEnv.ts b/packages/heterogeneous-agents/src/claudeCodeDirectEnv.ts
new file mode 100644
index 00000000000..74b3bcf34b6
--- /dev/null
+++ b/packages/heterogeneous-agents/src/claudeCodeDirectEnv.ts
@@ -0,0 +1,139 @@
+import type { AiProviderSDKType } from '@lobechat/types';
+
+export const CLAUDE_CODE_API_LOCAL_ONLY_ERROR =
+ 'Claude Code API mode is only supported for Desktop local execution.';
+
+export interface BuildClaudeCodeDirectEnvInput {
+ /** Decrypted provider credentials. This function is for trusted local execution only. */
+ keyVaults?: Record<string, unknown>;
+ model: string;
+ sdkType?: AiProviderSDKType | string;
+ smallFastModel?: string | null;
+}
+
+export interface BuildClaudeCodeDirectEnvResult {
+ env: Record<string, string>;
+ error?: string;
+}
+
+const DIRECT_AUTH_ENV_KEYS = [
+ 'ANTHROPIC_API_KEY',
+ 'ANTHROPIC_AUTH_TOKEN',
+ 'ANTHROPIC_BASE_URL',
+ 'ANTHROPIC_MODEL',
+ 'ANTHROPIC_SMALL_FAST_MODEL',
+ 'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST',
+ 'CLAUDE_CODE_SUBPROCESS_ENV_SCRUB',
+ 'CLAUDE_CODE_USE_BEDROCK',
+ 'CLAUDE_CODE_USE_MANTLE',
+ 'CLAUDE_CODE_USE_VERTEX',
+] as const;
+
+const pickNonEmptyString = (value: unknown): string | undefined => {
+ const stringValue = typeof value === 'string' ? value.trim() : undefined;
+ return stringValue || undefined;
+};
+
+/**
+ * Claude Code appends `/v1/messages` to `ANTHROPIC_BASE_URL`.
+ * LobeHub provider settings often store the SDK-style host (`…/v1` or `…/v1/messages`).
+ * Strip with linear string ops; quantified-slash regexes are ReDoS on user URLs.
+ */
+const ANTHROPIC_SDK_BASE_URL_SUFFIXES = ['/v1/messages', '/v1'] as const;
+const FIRST_PARTY_ANTHROPIC_HOSTS = new Set(['api.anthropic.com']);
+
+const stripTrailingSlashes = (value: string): string => {
+ let end = value.length;
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
+ return value.slice(0, end);
+};
+
+const normalizeClaudeCodeBaseURL = (baseURL: string): string | undefined => {
+ let normalized = stripTrailingSlashes(baseURL);
+ for (const suffix of ANTHROPIC_SDK_BASE_URL_SUFFIXES) {
+ if (!normalized.endsWith(suffix)) continue;
+ normalized = stripTrailingSlashes(normalized.slice(0, -suffix.length));
+ break;
+ }
+ return normalized || undefined;
+};
+
+const isFirstPartyAnthropicBaseURL = (baseURL?: string): boolean => {
+ if (!baseURL) return true;
+ try {
+ return FIRST_PARTY_ANTHROPIC_HOSTS.has(new URL(baseURL).hostname);
+ } catch {
+ return false;
+ }
+};
+
+/** Remove user-configured auth/model routing before applying a host-managed direct binding. */
+export const sanitizeClaudeCodeDirectEnv = (
+ source: Record<string, string> | undefined,
+): Record<string, string> => {
+ const env = { ...source };
+ for (const key of DIRECT_AUTH_ENV_KEYS) delete env[key];
+ return env;
+};
+
+/** Remove every persisted model override before applying the API-bound model. */
+export const sanitizeClaudeCodeDirectArgs = (source: string[] | undefined): string[] => {
+ const sourceArgs = source ?? [];
+ const args: string[] = [];
+
+ for (let index = 0; index < sourceArgs.length; index += 1) {
+ const arg = sourceArgs[index];
+ if (arg === '--model') {
+ index += 1;
+ continue;
+ }
+ if (arg.startsWith('--model=')) continue;
+ args.push(arg);
+ }
+
+ return args;
+};
+
+/**
+ * Resolve a LobeHub provider into Claude Code environment variables.
+ *
+ * This accepts decrypted credentials and must only run inside the trusted Desktop-local
+ * boundary. Remote targets must use an operation-scoped gateway instead.
+ */
+export const buildClaudeCodeDirectEnv = (
+ input: BuildClaudeCodeDirectEnvInput,
+): BuildClaudeCodeDirectEnvResult => {
+ const model = pickNonEmptyString(input.model);
+ if (!model) return { env: {}, error: 'Model id is required for Claude Code API mode.' };
+
+ if (input.sdkType !== 'anthropic') {
+ return {
+ env: {},
+ error: `Claude Code API mode does not support sdkType="${input.sdkType ?? 'unknown'}".`,
+ };
+ }
+
+ const apiKey = pickNonEmptyString(input.keyVaults?.apiKey);
+ if (!apiKey) {
+ return { env: {}, error: 'Provider apiKey is missing. Configure it in provider settings.' };
+ }
+
+ const baseURL = pickNonEmptyString(input.keyVaults?.baseURL);
+ const normalizedBaseURL = baseURL ? normalizeClaudeCodeBaseURL(baseURL) : undefined;
+ const useFirstPartyApiKey = isFirstPartyAnthropicBaseURL(normalizedBaseURL);
+
+ const env: Record<string, string> = {
+ ANTHROPIC_MODEL: model,
+ ANTHROPIC_SMALL_FAST_MODEL: pickNonEmptyString(input.smallFastModel) ?? model,
+ CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST: '1',
+ CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: '1',
+ CLAUDE_CODE_USE_BEDROCK: '0',
+ CLAUDE_CODE_USE_MANTLE: '0',
+ CLAUDE_CODE_USE_VERTEX: '0',
+ ...(useFirstPartyApiKey ? { ANTHROPIC_API_KEY: apiKey } : { ANTHROPIC_AUTH_TOKEN: apiKey }),
+ };
+
+ if (normalizedBaseURL) env.ANTHROPIC_BASE_URL = normalizedBaseURL;
+
+ return { env };
+};
diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.ts
index 11583784069..1133a980c25 100644
--- a/packages/heterogeneous-agents/src/index.ts
+++ b/packages/heterogeneous-agents/src/index.ts
@@ -5,6 +5,14 @@ export {
GrokBuildAdapter,
QoderAdapter,
} from './adapters';
+export {
+ buildClaudeCodeDirectEnv,
+ type BuildClaudeCodeDirectEnvInput,
+ type BuildClaudeCodeDirectEnvResult,
+ CLAUDE_CODE_API_LOCAL_ONLY_ERROR,
+ sanitizeClaudeCodeDirectArgs,
+ sanitizeClaudeCodeDirectEnv,
+} from './claudeCodeDirectEnv';
export type {
HeterogeneousAgentCliError,
HeterogeneousAgentDescriptor,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 2d35331c4c1..c06a7d40747 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -521,6 +521,19 @@ export default {
'heteroAgent.cloudNotConfigured.desc':
'Configure your Claude Code token in agent profile to start sending messages.',
'heteroAgent.cloudNotConfigured.title': 'Cloud credentials required',
+ 'heteroAgent.apiMode.configMissing':
+ 'Claude Code API mode requires a provider and model binding. Open the agent profile to configure it.',
+ 'heteroAgent.apiMode.labDisabled.action': 'Enable in Labs',
+ 'heteroAgent.apiMode.labDisabled.desc':
+ 'Turn it on in Settings → Labs, or switch this agent to Subscription authentication.',
+ 'heteroAgent.apiMode.labDisabled.title': 'Claude Code API mode is a Labs experiment',
+ 'heteroAgent.apiMode.localOnly.desc':
+ 'Switch the execution environment to Local device, or use Subscription authentication.',
+ 'heteroAgent.apiMode.localOnly.title': 'API mode requires Desktop local execution',
+ 'heteroAgent.apiMode.modelUnavailable':
+ 'The model "{{providerId}}/{{model}}" is disabled or no longer available.',
+ 'heteroAgent.apiMode.providerUnavailable':
+ 'The provider "{{providerId}}" is disabled or no longer available.',
'heteroAgent.cloudRepo.sectionTitle': 'Repositories',
'heteroAgent.cloudRepo.notSet': 'No repo selected',
'heteroAgent.cloudRepo.noRepos': 'No repositories configured. Add them in agent settings.',
diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.ts
index cc0b413d17b..8bbccb097be 100644
--- a/packages/locales/src/default/labs.ts
+++ b/packages/locales/src/default/labs.ts
@@ -13,6 +13,9 @@ export default {
'features.assistantMessageGroup.desc':
'Group agent messages and their tool call results together for display',
'features.assistantMessageGroup.title': 'Agent Message Grouping',
+ 'features.claudeCodeApiMode.desc':
+ 'Let Claude Code use a configured API provider and model on this desktop instead of a Claude subscription. Desktop local execution only.',
+ 'features.claudeCodeApiMode.title': 'Claude Code API Provider',
'features.claudeCodeSdk.desc':
'Run Claude Code sessions through the Claude Agent SDK instead of spawning the CLI. Enables richer streaming and session control.',
'features.claudeCodeSdk.title': 'Claude Code SDK Runtime',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index b3f69a5cd8d..c4a074aeccb 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -360,6 +360,19 @@ export default {
// Heterogeneous agent CLI status (shown on agent profile page in integration mode)
'heterogeneousStatus.account.label': 'Account',
+ 'heterogeneousStatus.apiMode.configureProvider': 'Go to provider settings',
+ 'heterogeneousStatus.apiMode.enableInLabs': 'Enable in Labs',
+ 'heterogeneousStatus.apiMode.labDisabled':
+ 'API authentication is a Labs experiment. Enable it to use a configured provider instead of a Claude subscription.',
+ 'heterogeneousStatus.apiMode.localOnly': 'Available only for Desktop local execution',
+ 'heterogeneousStatus.apiMode.model': 'Model',
+ 'heterogeneousStatus.apiMode.modelPlaceholder': 'Select a model',
+ 'heterogeneousStatus.apiMode.noProviders':
+ 'No enabled provider with an Anthropic-compatible endpoint is configured.',
+ 'heterogeneousStatus.apiMode.smallFastModel': 'Background model',
+ 'heterogeneousStatus.apiMode.smallFastModelDesc':
+ 'Used for session titles, summaries, and other background work. Does not change the main conversation.',
+ 'heterogeneousStatus.apiMode.smallFastModelPlaceholder': 'Same as primary model',
'heterogeneousStatus.auth.api': 'API',
'heterogeneousStatus.auth.label': 'Auth Method',
'heterogeneousStatus.auth.subscription': 'Subscription',
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index 30e4de6fad0..d4c8f897eff 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -75,6 +75,22 @@ export interface HeterogeneousAgentModelCatalogFailure {
export type HeterogeneousAgentModelCatalog =
HeterogeneousAgentModelCatalogFailure | HeterogeneousAgentModelCatalogSuccess;
+/** Authentication source used by a heterogeneous agent CLI. */
+export type HeterogeneousAuthMode = 'api' | 'subscription';
+
+/**
+ * Reference-only API binding for a heterogeneous agent.
+ * Provider credentials are resolved at launch and are never persisted here.
+ */
+export interface HeterogeneousApiConfig {
+ /** Primary model used by the CLI. */
+ model: string;
+ /** LobeHub provider whose runtime credentials are resolved locally. */
+ providerId: string;
+ /** Optional model used for fast/background work. Defaults to the primary model. */
+ smallFastModel?: string | null;
+}
+
/**
* Heterogeneous agent provider configuration.
* When set, the assistant delegates execution to an external agent runtime
@@ -92,8 +108,12 @@ export type HeterogeneousAgentModelCatalog =
* when it is `device`. `platformAgentId` selects the named platform agent.
*/
export interface HeterogeneousProviderConfig {
+ /** API binding. Only used by Claude Code when `authMode` is `api`. */
+ apiConfig?: HeterogeneousApiConfig;
/** Additional CLI arguments for the agent command (local CLI only). */
args?: string[];
+ /** Defaults to `subscription` for backwards compatibility. */
+ authMode?: HeterogeneousAuthMode;
/** Command to spawn the agent (e.g. 'claude') (local CLI only). */
command?: string;
/**
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 0f97b75febc..62452cfa76a 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -161,6 +161,10 @@ export const UserLabSchema = z.object({
* enable artifact deployment features (publish artifacts to a hosted URL)
*/
enableArtifactDeployment: z.boolean().optional(),
+ /**
+ * let Claude Code use a configured API provider on Desktop instead of a subscription
+ */
+ enableClaudeCodeApiMode: z.boolean().optional(),
/**
* run Claude Code hetero sessions through the Claude Agent SDK instead of CLI spawn
*/
diff --git a/src/features/HeterogeneousAgent/hooks/useClaudeCodeCompatibleProviders.ts b/src/features/HeterogeneousAgent/hooks/useClaudeCodeCompatibleProviders.ts
new file mode 100644
index 00000000000..1a06f467920
--- /dev/null
+++ b/src/features/HeterogeneousAgent/hooks/useClaudeCodeCompatibleProviders.ts
@@ -0,0 +1,69 @@
+import type { HeterogeneousApiConfig } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { useMemo } from 'react';
+
+import { validateClaudeCodeApiBinding } from '@/helpers/claudeCodeApiBinding';
+import { useAiInfraStore } from '@/store/aiInfra';
+import { aiProviderSelectors } from '@/store/aiInfra/selectors';
+
+export interface ClaudeCodeCompatibleProvider {
+ id: string;
+ name?: string;
+}
+
+export interface ClaudeCodeCompatibleModel {
+ displayName?: string;
+ id: string;
+ providerId: string;
+}
+
+interface ClaudeCodeCompatibleProvidersResult {
+ modelsByProvider: Record<string, ClaudeCodeCompatibleModel[]>;
+ providers: ClaudeCodeCompatibleProvider[];
+}
+
+export const useClaudeCodeApiBindingValidation = (apiConfig?: HeterogeneousApiConfig) => {
+ const isReady = useAiInfraStore(aiProviderSelectors.isInitAiProviderRuntimeState);
+ const providerList = useAiInfraStore((state) => state.enabledAiProviders ?? [], isEqual);
+ const runtimeConfig = useAiInfraStore((state) => state.aiProviderRuntimeConfig, isEqual);
+ const enabledModels = useAiInfraStore((state) => state.enabledAiModels ?? [], isEqual);
+ const providerConfig = apiConfig ? runtimeConfig[apiConfig.providerId] : undefined;
+
+ return {
+ error: validateClaudeCodeApiBinding({
+ apiConfig,
+ enabledModels,
+ providerEnabled: !!apiConfig && providerList.some(({ id }) => id === apiConfig.providerId),
+ providerSdkType: providerConfig?.settings.sdkType,
+ }),
+ isReady,
+ };
+};
+
+/** Providers that the Desktop-local direct adapter can currently launch. */
+export const useClaudeCodeCompatibleProviders = (): ClaudeCodeCompatibleProvidersResult => {
+ const providerList = useAiInfraStore((state) => state.enabledAiProviders ?? [], isEqual);
+ const runtimeConfig = useAiInfraStore((state) => state.aiProviderRuntimeConfig, isEqual);
+ const enabledModels = useAiInfraStore((state) => state.enabledAiModels ?? [], isEqual);
+
+ return useMemo(() => {
+ const candidateProviders = providerList
+ .filter((provider) => runtimeConfig[provider.id]?.settings.sdkType === 'anthropic')
+ .map(({ id, name }) => ({ id, name }));
+ const compatibleProviderIds = new Set(candidateProviders.map(({ id }) => id));
+ const modelsByProvider: Record<string, ClaudeCodeCompatibleModel[]> = {};
+
+ for (const model of enabledModels) {
+ if (model.type !== 'chat' || !compatibleProviderIds.has(model.providerId)) continue;
+ modelsByProvider[model.providerId] ??= [];
+ modelsByProvider[model.providerId].push({
+ displayName: model.displayName,
+ id: model.id,
+ providerId: model.providerId,
+ });
+ }
+
+ const providers = candidateProviders.filter(({ id }) => modelsByProvider[id]?.length);
+ return { modelsByProvider, providers };
+ }, [enabledModels, providerList, runtimeConfig]);
+};
diff --git a/src/features/ModelSelect/index.tsx b/src/features/ModelSelect/index.tsx
index 1dbaf26555d..28a17defcb9 100644
--- a/src/features/ModelSelect/index.tsx
+++ b/src/features/ModelSelect/index.tsx
@@ -88,6 +88,8 @@ interface ModelSelectProps extends Pick<
/** Fired when the selection is cleared via `allowClear`. */
onClear?: () => void;
popupWidth?: number;
+ /** Restrict selection to these provider ids. */
+ providerIds?: string[];
requiredAbilities?: (keyof EnabledProviderWithModels['children'][number]['abilities'])[];
showAbility?: boolean;
/** `undefined` renders the empty state (`placeholder`) instead of a selection. */
@@ -111,14 +113,20 @@ const ModelSelect = memo<ModelSelectProps>(
initialWidth = false,
popupWidth,
modelType = 'chat',
+ providerIds,
}) => {
const { t } = useTranslation('components');
const [enabling, setEnabling] = useState(false);
- const enabledList = useAiInfraStore((s) =>
+ const fullEnabledList = useAiInfraStore((s) =>
modelType === 'embedding'
? aiProviderSelectors.enabledEmbeddingModelList(s)
: s.enabledChatModelList || [],
);
+ const enabledList = useMemo(() => {
+ if (!providerIds) return fullEnabledList;
+ const allowedProviderIds = new Set(providerIds);
+ return fullEnabledList.filter((provider) => allowedProviderIds.has(provider.id));
+ }, [fullEnabledList, providerIds]);
const builtinAiModelList = useAiInfraStore((s) => s.builtinAiModelList);
const modelRedirects = useAiInfraStore((s) => s.modelRedirects);
const enabledAiProviders = useAiInfraStore((s) => s.enabledAiProviders);
diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.ts
index 11e61bd378a..77a603617fc 100644
--- a/src/features/Settings/labs/features.ts
+++ b/src/features/Settings/labs/features.ts
@@ -14,6 +14,7 @@ export type LabStage = 'alpha' | 'beta';
type LabFeatureI18nKey =
| 'agentGraphConfig'
| 'artifactDeployment'
+ | 'claudeCodeApiMode'
| 'claudeCodeSdk'
| 'codexAppServer'
| 'desktopSplitView'
@@ -108,6 +109,13 @@ export const LAB_FEATURES: LabFeatureItem[] = [
searchKeywords: ['imessage', 'bluebubbles'],
stage: 'alpha',
},
+ {
+ desktopOnly: true,
+ flag: 'enableClaudeCodeApiMode',
+ i18nKey: 'claudeCodeApiMode',
+ searchKeywords: ['claude code api', 'api provider', 'api mode'],
+ stage: 'alpha',
+ },
{
desktopOnly: true,
flag: 'enableClaudeCodeSdk',
diff --git a/src/features/Settings/labs/index.test.tsx b/src/features/Settings/labs/index.test.tsx
index 18c08ac40a7..3c2c4045128 100644
--- a/src/features/Settings/labs/index.test.tsx
+++ b/src/features/Settings/labs/index.test.tsx
@@ -166,12 +166,15 @@ describe('Labs settings page', () => {
const alphaTags = screen.getAllByText('stage.alpha.label');
const betaTags = screen.getAllByText('stage.beta.label');
// Every toggle carries exactly one stage tag.
- expect(alphaTags.length + betaTags.length).toBe(14);
+ expect(alphaTags.length + betaTags.length).toBe(15);
});
it('marks internal-testing experiments as alpha and usable ones as beta', () => {
renderPage();
+ const claudeCodeApiMode = screen.getByText('features.claudeCodeApiMode.title');
+ expect(within(claudeCodeApiMode).getByText('stage.alpha.label')).toBeDefined();
+
const claudeCodeSdk = screen.getByText('features.claudeCodeSdk.title');
expect(within(claudeCodeSdk).getByText('stage.alpha.label')).toBeDefined();
diff --git a/src/helpers/claudeCodeApiBinding.test.ts b/src/helpers/claudeCodeApiBinding.test.ts
new file mode 100644
index 00000000000..25458ef5544
--- /dev/null
+++ b/src/helpers/claudeCodeApiBinding.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ resolveClaudeCodeApiBindingGuard,
+ validateClaudeCodeApiBinding,
+} from './claudeCodeApiBinding';
+
+const enabledModels = [
+ { id: 'claude-fast', providerId: 'anthropic', type: 'chat' },
+ { id: 'claude-primary', providerId: 'anthropic', type: 'chat' },
+];
+
+describe('validateClaudeCodeApiBinding', () => {
+ it('accepts an enabled Anthropic provider and both bound models', () => {
+ expect(
+ validateClaudeCodeApiBinding({
+ apiConfig: {
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ smallFastModel: 'claude-fast',
+ },
+ enabledModels,
+ providerEnabled: true,
+ providerSdkType: 'anthropic',
+ }),
+ ).toBeUndefined();
+ });
+
+ it('reports missing configuration', () => {
+ expect(
+ validateClaudeCodeApiBinding({
+ apiConfig: undefined,
+ enabledModels,
+ providerEnabled: false,
+ }),
+ ).toEqual({ code: 'configMissing' });
+ });
+
+ it('rejects disabled and non-Anthropic providers', () => {
+ expect(
+ validateClaudeCodeApiBinding({
+ apiConfig: { model: 'claude-primary', providerId: 'anthropic' },
+ enabledModels,
+ providerEnabled: true,
+ providerSdkType: 'openai',
+ }),
+ ).toEqual({ code: 'providerUnavailable', providerId: 'anthropic' });
+ });
+
+ it('rejects a stale explicit fast model but treats null as the primary-model default', () => {
+ expect(
+ validateClaudeCodeApiBinding({
+ apiConfig: {
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ smallFastModel: 'removed-fast-model',
+ },
+ enabledModels,
+ providerEnabled: true,
+ providerSdkType: 'anthropic',
+ }),
+ ).toEqual({
+ code: 'modelUnavailable',
+ model: 'removed-fast-model',
+ providerId: 'anthropic',
+ });
+
+ expect(
+ validateClaudeCodeApiBinding({
+ apiConfig: { model: 'claude-primary', providerId: 'anthropic', smallFastModel: null },
+ enabledModels,
+ providerEnabled: true,
+ providerSdkType: 'anthropic',
+ }),
+ ).toBeUndefined();
+ });
+});
+
+describe('resolveClaudeCodeApiBindingGuard', () => {
+ it('blocks local API sending while provider state loads and when the binding is invalid', () => {
+ expect(resolveClaudeCodeApiBindingGuard({ active: true, isReady: false })).toEqual({
+ blocked: true,
+ error: undefined,
+ });
+
+ const error = { code: 'configMissing' } as const;
+ expect(resolveClaudeCodeApiBindingGuard({ active: true, error, isReady: true })).toEqual({
+ blocked: true,
+ error,
+ });
+ });
+
+ it('does not block other modes or a valid initialized binding', () => {
+ expect(resolveClaudeCodeApiBindingGuard({ active: false, isReady: false }).blocked).toBe(false);
+ expect(resolveClaudeCodeApiBindingGuard({ active: true, isReady: true }).blocked).toBe(false);
+ });
+});
diff --git a/src/helpers/claudeCodeApiBinding.ts b/src/helpers/claudeCodeApiBinding.ts
new file mode 100644
index 00000000000..9d0d6071253
--- /dev/null
+++ b/src/helpers/claudeCodeApiBinding.ts
@@ -0,0 +1,69 @@
+import type { HeterogeneousApiConfig } from '@lobechat/types';
+
+interface EnabledChatModelRef {
+ id: string;
+ providerId: string;
+ type: string;
+}
+
+interface ValidateClaudeCodeApiBindingInput {
+ apiConfig?: HeterogeneousApiConfig;
+ enabledModels: readonly EnabledChatModelRef[];
+ providerEnabled: boolean;
+ providerSdkType?: string;
+}
+
+export type ClaudeCodeApiBindingError =
+ | { code: 'configMissing' }
+ | { code: 'modelUnavailable'; model: string; providerId: string }
+ | { code: 'providerUnavailable'; providerId: string };
+
+interface ResolveClaudeCodeApiBindingGuardInput {
+ active: boolean;
+ error?: ClaudeCodeApiBindingError;
+ isReady: boolean;
+}
+
+export const resolveClaudeCodeApiBindingGuard = ({
+ active,
+ error,
+ isReady,
+}: ResolveClaudeCodeApiBindingGuardInput) => ({
+ blocked: active && (!isReady || !!error),
+ error: active && isReady ? error : undefined,
+});
+
+/** Validate the reference-only binding shared by the chat guard and Desktop-local spawn. */
+export const validateClaudeCodeApiBinding = ({
+ apiConfig,
+ enabledModels,
+ providerEnabled,
+ providerSdkType,
+}: ValidateClaudeCodeApiBindingInput): ClaudeCodeApiBindingError | undefined => {
+ if (!apiConfig?.providerId || !apiConfig.model) return { code: 'configMissing' };
+
+ if (!providerEnabled || providerSdkType !== 'anthropic') {
+ return { code: 'providerUnavailable', providerId: apiConfig.providerId };
+ }
+
+ const boundModels = [apiConfig.model, apiConfig.smallFastModel].filter(
+ (model): model is string => !!model,
+ );
+ const unavailableModel = boundModels.find(
+ (boundModel) =>
+ !enabledModels.some(
+ (model) =>
+ model.providerId === apiConfig.providerId &&
+ model.id === boundModel &&
+ model.type === 'chat',
+ ),
+ );
+
+ return unavailableModel
+ ? {
+ code: 'modelUnavailable',
+ model: unavailableModel,
+ providerId: apiConfig.providerId,
+ }
+ : undefined;
+};
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx
new file mode 100644
index 00000000000..869f7a48bea
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx
@@ -0,0 +1,66 @@
+'use client';
+
+import type { HeterogeneousApiConfig } from '@lobechat/types';
+import { memo, useMemo } from 'react';
+
+import { useClaudeCodeCompatibleProviders } from '@/features/HeterogeneousAgent/hooks/useClaudeCodeCompatibleProviders';
+import ModelSelect from '@/features/ModelSelect';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+interface ApiModeModelBarProps {
+ agentId: string;
+}
+
+const ApiModeModelBar = memo<ApiModeModelBarProps>(({ agentId }) => {
+ const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ const updateAgentConfigById = useAgentStore((state) => state.updateAgentConfigById);
+ const { providers } = useClaudeCodeCompatibleProviders();
+ const providerIds = useMemo(() => providers.map(({ id }) => id), [providers]);
+ const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
+
+ if (
+ heterogeneousProvider?.type !== 'claude-code' ||
+ heterogeneousProvider.authMode !== 'api' ||
+ providerIds.length === 0
+ )
+ return null;
+
+ const persist = async (apiConfig: HeterogeneousApiConfig) => {
+ await updateAgentConfigById(agentId, {
+ agencyConfig: {
+ ...agencyConfig,
+ heterogeneousProvider: { ...heterogeneousProvider, apiConfig },
+ },
+ });
+ };
+
+ return (
+ <ModelSelect
+ initialWidth
+ popupWidth={360}
+ providerIds={providerIds}
+ size="small"
+ variant="borderless"
+ value={
+ heterogeneousProvider.apiConfig
+ ? {
+ model: heterogeneousProvider.apiConfig.model,
+ provider: heterogeneousProvider.apiConfig.providerId,
+ }
+ : undefined
+ }
+ onChange={({ model, provider }) => {
+ const smallFastModel =
+ heterogeneousProvider.apiConfig?.providerId === provider
+ ? heterogeneousProvider.apiConfig.smallFastModel
+ : undefined;
+ void persist({ model, providerId: provider, smallFastModel });
+ }}
+ />
+ );
+});
+
+ApiModeModelBar.displayName = 'ApiModeModelBar';
+
+export default ApiModeModelBar;
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index 8c25a813005..749dc5af9c3 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -14,8 +14,10 @@ import { type ActionKeys } from '@/features/ChatInput';
import HeteroModel from '@/features/ChatInput/ControlBar/HeteroModel';
import { ChatInput } from '@/features/Conversation';
import { contextSelectors, useConversationStore } from '@/features/Conversation/store';
+import { useClaudeCodeApiBindingValidation } from '@/features/HeterogeneousAgent/hooks/useClaudeCodeCompatibleProviders';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { resolveClaudeCodeApiBindingGuard } from '@/helpers/claudeCodeApiBinding';
import {
isHeterogeneousSandboxExecutionAvailable,
resolveExecutionTarget,
@@ -23,7 +25,10 @@ import {
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useRemoteAgentDeviceGuard } from '@/hooks/useRemoteAgentDeviceGuard';
import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+import ApiModeModelBar from './ApiModeModelBar';
import HeteroControlBar from './HeteroControlBar';
import HeteroPlus from './HeteroPlus';
import ScheduledSendChip from './ScheduledSendChip';
@@ -95,18 +100,25 @@ const HeterogeneousChatInput = memo(() => {
// the shared row — hold the input closed (below) instead of gating device
// runs off a value that can flip once the override arrives.
const { agencyConfig, isPreferenceLoading, workspaceScoped } = useEffectiveAgencyConfig(agentId);
- const providerType = agencyConfig?.heterogeneousProvider?.type;
+ const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
+ const providerType = heterogeneousProvider?.type;
+ const enableClaudeCodeApiMode = useUserStore(labPreferSelectors.enableClaudeCodeApiMode);
+ const isApiAuth = providerType === 'claude-code' && heterogeneousProvider?.authMode === 'api';
+ const isApiModeActive = isApiAuth && enableClaudeCodeApiMode;
const executionTarget = resolveExecutionTarget(agencyConfig, {
isHetero: !!providerType,
clientExecutionAvailable: isDesktop,
workspaceScoped,
});
+ const { error: apiBindingValidationError, isReady: isApiBindingStateReady } =
+ useClaudeCodeApiBindingValidation(heterogeneousProvider?.apiConfig);
const deviceSelectionRequired =
!!providerType &&
!isHeterogeneousSandboxExecutionAvailable(providerType) &&
executionTarget === 'none';
const showHeteroModel =
+ !isApiAuth &&
isHeteroSelectorAvailable(providerType) &&
shouldShowHeteroModelSelector({
boundDeviceId: agencyConfig?.boundDeviceId,
@@ -114,6 +126,16 @@ const HeterogeneousChatInput = memo(() => {
isDesktopClient: isDesktop,
providerType,
});
+ const showApiModeModel = !!agentId && isApiModeActive && executionTarget === 'local';
+ const apiModeLabDisabled = isApiAuth && !enableClaudeCodeApiMode;
+ const apiModeTargetUnsupported = isApiModeActive && executionTarget !== 'local';
+ const isLocalApiMode = isApiModeActive && executionTarget === 'local';
+ const { blocked: apiModeBindingBlocked, error: apiModeBindingError } =
+ resolveClaudeCodeApiBindingGuard({
+ active: isLocalApiMode,
+ error: apiBindingValidationError,
+ isReady: isApiBindingStateReady,
+ });
// The armed-schedule chip sits immediately after the `+` that armed it, so the
// state and the control that produced it read as one unit.
const extraActionItems = useMemo<ChatInputActionsProps['items']>(
@@ -128,8 +150,13 @@ const HeterogeneousChatInput = memo(() => {
// (left-aligned) action bar, so it sits right next to Send — it qualifies the
// run the send button is about to commit.
const sendAreaPrefix = useMemo(
- () => (showHeteroModel ? <HeteroModel /> : undefined),
- [showHeteroModel],
+ () =>
+ showApiModeModel ? (
+ <ApiModeModelBar agentId={agentId} />
+ ) : showHeteroModel ? (
+ <HeteroModel />
+ ) : undefined,
+ [agentId, showApiModeModel, showHeteroModel],
);
// A run goes to an `lh connect` device when its execution target resolves to a
@@ -189,7 +216,14 @@ const HeterogeneousChatInput = memo(() => {
const renderCloudConfigGuard = () => {
// Until the override loads, `isDeviceExecution` may be a false negative —
// don't flash the cloud-config prompt for what turns out to be a device run.
- if (isPreferenceLoading || deviceSelectionRequired || isDeviceExecution || isConfigured) {
+ if (
+ apiModeLabDisabled ||
+ apiModeTargetUnsupported ||
+ isPreferenceLoading ||
+ deviceSelectionRequired ||
+ isDeviceExecution ||
+ isConfigured
+ ) {
return null;
}
@@ -206,6 +240,58 @@ const HeterogeneousChatInput = memo(() => {
);
};
+ const renderApiModeLabGuard = () => {
+ if (!apiModeLabDisabled) return null;
+
+ return (
+ <GuardBanner
+ hint={t('heteroAgent.apiMode.labDisabled.desc')}
+ title={t('heteroAgent.apiMode.labDisabled.title')}
+ action={
+ <Button size={'small'} type={'primary'} onClick={() => navigate('/settings/labs')}>
+ {t('heteroAgent.apiMode.labDisabled.action')}
+ </Button>
+ }
+ />
+ );
+ };
+
+ const renderApiModeTargetGuard = () => {
+ if (!apiModeTargetUnsupported) return null;
+
+ return (
+ <GuardBanner
+ hint={t('heteroAgent.apiMode.localOnly.desc')}
+ title={t('heteroAgent.apiMode.localOnly.title')}
+ action={
+ <Button size={'small'} type={'primary'} onClick={goToAgentProfile}>
+ {t('platformAgent.deviceGuard.configure')}
+ </Button>
+ }
+ />
+ );
+ };
+
+ const renderApiModeBindingGuard = () => {
+ if (!apiModeBindingError) return null;
+
+ const title =
+ apiModeBindingError.code === 'configMissing'
+ ? t('heteroAgent.apiMode.configMissing')
+ : t(`heteroAgent.apiMode.${apiModeBindingError.code}`, apiModeBindingError);
+
+ return (
+ <GuardBanner
+ title={title}
+ action={
+ <Button size={'small'} type={'primary'} onClick={goToAgentProfile}>
+ {t('platformAgent.deviceGuard.configure')}
+ </Button>
+ }
+ />
+ );
+ };
+
const renderDeviceSelectionGuard = () => {
if (!deviceSelectionRequired) return null;
@@ -224,15 +310,26 @@ const HeterogeneousChatInput = memo(() => {
// workspace preference loads, keep send disabled: the effective target isn't
// known yet, so neither guard can vouch for the run.
const inputDisabled =
+ apiModeLabDisabled ||
+ apiModeTargetUnsupported ||
+ apiModeBindingBlocked ||
isPreferenceLoading ||
deviceSelectionRequired ||
(!isConfigured && !isDeviceExecution) ||
deviceBlocked;
const hasGuard =
- deviceSelectionRequired || deviceBlocked || (!isConfigured && !isDeviceExecution);
+ apiModeLabDisabled ||
+ apiModeTargetUnsupported ||
+ !!apiModeBindingError ||
+ deviceSelectionRequired ||
+ deviceBlocked ||
+ (!isConfigured && !isDeviceExecution);
return (
<Flexbox>
+ {renderApiModeLabGuard()}
+ {renderApiModeTargetGuard()}
+ {renderApiModeBindingGuard()}
{renderDeviceSelectionGuard()}
{renderCloudConfigGuard()}
{renderDeviceGuard()}
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
index 4dab54e806f..ba2b421f8d9 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
@@ -99,6 +99,31 @@ vi.mock('@lobehub/ui', () => ({
Tooltip: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
}));
+vi.mock('@lobehub/ui/base-ui', () => ({
+ Segmented: ({
+ disabled,
+ onChange,
+ options,
+ }: {
+ disabled?: boolean;
+ onChange?: (value: string) => void;
+ options: Array<{ disabled?: boolean; label: ReactNode; value: string }>;
+ }) => (
+ <div>
+ {options.map((option) => (
+ <button
+ disabled={disabled || option.disabled}
+ key={option.value}
+ type="button"
+ onClick={() => onChange?.(option.value)}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ ),
+}));
+
vi.mock('antd-style', () => ({
createStaticStyles: () => ({
card: 'card',
@@ -122,6 +147,9 @@ vi.mock('react-i18next', () => ({
(
({
'heterogeneousStatus.account.label': 'Account',
+ 'heterogeneousStatus.apiMode.enableInLabs': 'Enable in Labs',
+ 'heterogeneousStatus.apiMode.labDisabled':
+ 'API authentication is a Labs experiment. Enable it to use a configured provider instead of a Claude subscription.',
'heterogeneousStatus.auth.api': 'API',
'heterogeneousStatus.auth.label': 'Auth Method',
'heterogeneousStatus.auth.subscription': 'Subscription',
@@ -143,6 +171,28 @@ vi.mock('@/features/Electron/HeterogeneousAgent/StatusGuide', () => ({
),
}));
+vi.mock('@/features/HeterogeneousAgent/hooks/useClaudeCodeCompatibleProviders', () => ({
+ useClaudeCodeCompatibleProviders: () => ({
+ modelsByProvider: {
+ anthropic: [{ id: 'claude-primary', providerId: 'anthropic' }],
+ },
+ providers: [{ id: 'anthropic', name: 'Anthropic' }],
+ }),
+}));
+
+vi.mock('@/features/ModelSelect', () => ({
+ default: ({ allowClear, onClear }: { allowClear?: boolean; onClear?: () => void }) => (
+ <div>
+ Model Select
+ {allowClear && (
+ <button type="button" onClick={onClear}>
+ Clear model
+ </button>
+ )}
+ </div>
+ ),
+}));
+
vi.mock('@/services/electron/binary', () => ({
binaryService: {
detectHeterogeneousAgentCommand,
@@ -322,8 +372,7 @@ describe('HeterogeneousAgentStatusCard', () => {
});
expect(screen.getByText('claude-alt')).toBeInTheDocument();
- expect(screen.getByText('Auth Method')).toBeInTheDocument();
- expect(screen.getByText('Subscription')).toBeInTheDocument();
+ expect(screen.queryByText('Auth Method')).not.toBeInTheDocument();
expect(screen.getByText('Plan')).toBeInTheDocument();
expect(screen.getByText('MAX')).toBeInTheDocument();
expect(screen.getByText('[email protected]')).toBeInTheDocument();
@@ -401,4 +450,88 @@ describe('HeterogeneousAgentStatusCard', () => {
expect(await screen.findByDisplayValue('claude')).toBeInTheDocument();
});
+
+ it('shows API authentication only after the Labs experiment is enabled', async () => {
+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: true });
+ getClaudeAuthStatus.mockResolvedValue(null);
+ const provider = {
+ command: 'claude',
+ type: 'claude-code',
+ } satisfies HeterogeneousProviderConfig;
+
+ const { rerender } = render(
+ <MemoryRouter>
+ <HeterogeneousAgentStatusCard apiModeAvailable provider={provider} />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText('claude')).toBeInTheDocument();
+ });
+ expect(screen.queryByText('Auth Method')).not.toBeInTheDocument();
+
+ rerender(
+ <MemoryRouter>
+ <HeterogeneousAgentStatusCard apiModeAvailable apiModeLabEnabled provider={provider} />
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByText('Auth Method')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'API' })).toBeEnabled();
+ });
+
+ it('keeps leftover API mode visible so the agent can switch back when Labs is off', async () => {
+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: true });
+ const provider = {
+ apiConfig: { model: 'claude-primary', providerId: 'anthropic' },
+ authMode: 'api',
+ command: 'claude',
+ type: 'claude-code',
+ } satisfies HeterogeneousProviderConfig;
+
+ render(
+ <MemoryRouter>
+ <HeterogeneousAgentStatusCard apiModeAvailable provider={provider} />
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByText('Auth Method')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'API' })).toBeDisabled();
+ expect(screen.getByText('Enable in Labs')).toBeInTheDocument();
+ expect(screen.queryByText('Model Select')).not.toBeInTheDocument();
+ });
+
+ it('persists null when clearing the small-fast model', async () => {
+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: true });
+ const onApiConfigChange = vi.fn();
+ const provider = {
+ apiConfig: {
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ smallFastModel: 'claude-fast',
+ },
+ authMode: 'api',
+ command: 'claude',
+ type: 'claude-code',
+ } satisfies HeterogeneousProviderConfig;
+
+ render(
+ <MemoryRouter>
+ <HeterogeneousAgentStatusCard
+ apiModeAvailable
+ apiModeLabEnabled
+ provider={provider}
+ onApiConfigChange={onApiConfigChange}
+ />
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Clear model' }));
+
+ expect(onApiConfigChange).toHaveBeenCalledWith({
+ model: 'claude-primary',
+ providerId: 'anthropic',
+ smallFastModel: null,
+ });
+ });
});
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
index a54d66071d6..77c41bc67a8 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
@@ -6,14 +6,21 @@ import {
getHeterogeneousAgentClientConfig,
isRemoteHeterogeneousType,
} from '@lobechat/heterogeneous-agents/client';
-import type { HeterogeneousProviderConfig } from '@lobechat/types';
+import type {
+ HeterogeneousApiConfig,
+ HeterogeneousAuthMode,
+ HeterogeneousProviderConfig,
+} from '@lobechat/types';
import { ActionIcon, CopyButton, Flexbox, Icon, Input, Tag, Text, Tooltip } from '@lobehub/ui';
+import { Segmented } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { Loader2Icon, PencilLine, RefreshCw, XCircle } from 'lucide-react';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';
+import { useClaudeCodeCompatibleProviders } from '@/features/HeterogeneousAgent/hooks/useClaudeCodeCompatibleProviders';
+import ModelSelect from '@/features/ModelSelect';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
import { binaryService } from '@/services/electron/binary';
@@ -209,12 +216,23 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface HeterogeneousAgentStatusCardProps {
+ apiModeAvailable?: boolean;
+ apiModeLabEnabled?: boolean;
+ onApiConfigChange?: (apiConfig: HeterogeneousApiConfig | undefined) => Promise<void> | void;
+ onAuthModeChange?: (authMode: HeterogeneousAuthMode) => Promise<void> | void;
onCommandChange?: (command: string) => Promise<void> | void;
provider: HeterogeneousProviderConfig;
}
const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
- ({ provider, onCommandChange }) => {
+ ({
+ apiModeAvailable = false,
+ apiModeLabEnabled = false,
+ provider,
+ onApiConfigChange,
+ onAuthModeChange,
+ onCommandChange,
+ }) => {
const { t } = useTranslation('setting');
const navigate = useWorkspaceAwareNavigate();
const { allowed: canEdit } = usePermission('edit_own_content');
@@ -229,6 +247,12 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
const [isEditingCommand, setIsEditingCommand] = useState(false);
const [savingCommand, setSavingCommand] = useState(false);
const commandInputRef = useRef<HTMLInputElement | null>(null);
+ const authMode = provider.authMode ?? 'subscription';
+ const { modelsByProvider, providers: compatibleProviders } = useClaudeCodeCompatibleProviders();
+ const compatibleProviderIds = useMemo(
+ () => compatibleProviders.map(({ id }) => id),
+ [compatibleProviders],
+ );
const displayName = providerConfig?.title || provider.type;
const AgentIcon = providerConfig?.icon;
@@ -247,20 +271,52 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
!status?.available &&
!isUsingCustomCommand;
- const fetchAuth = useCallback(async () => {
- if (provider.type !== 'claude-code') {
- setAuth(null);
- return;
- }
+ const handleAuthModeChange = useCallback(
+ async (nextAuthMode: HeterogeneousAuthMode) => {
+ if (!canEdit || nextAuthMode === authMode) return;
+ if (nextAuthMode === 'api' && (!apiModeLabEnabled || !apiModeAvailable)) return;
- try {
- const result = await binaryService.getClaudeAuthStatus(resolvedCommand);
- setAuth(result);
- } catch (error) {
- console.warn('[HeterogeneousAgentStatusCard] Failed to get Claude auth status:', error);
- setAuth(null);
- }
- }, [provider.type, resolvedCommand]);
+ await onAuthModeChange?.(nextAuthMode);
+ if (nextAuthMode !== 'api' || provider.apiConfig) return;
+
+ const firstProvider = compatibleProviders[0];
+ const firstModel = firstProvider && modelsByProvider[firstProvider.id]?.[0];
+ if (firstProvider && firstModel) {
+ await onApiConfigChange?.({ model: firstModel.id, providerId: firstProvider.id });
+ }
+ },
+ [
+ apiModeAvailable,
+ apiModeLabEnabled,
+ authMode,
+ canEdit,
+ compatibleProviders,
+ modelsByProvider,
+ onApiConfigChange,
+ onAuthModeChange,
+ provider.apiConfig,
+ ],
+ );
+
+ const handlePrimaryModelChange = useCallback(
+ async ({ model, provider: providerId }: { model: string; provider: string }) => {
+ if (!canEdit) return;
+ const smallFastModel =
+ provider.apiConfig?.providerId === providerId
+ ? provider.apiConfig.smallFastModel
+ : undefined;
+ await onApiConfigChange?.({ model, providerId, smallFastModel });
+ },
+ [canEdit, onApiConfigChange, provider.apiConfig],
+ );
+
+ const handleSmallFastModelChange = useCallback(
+ async (smallFastModel: string | null) => {
+ if (!canEdit || !provider.apiConfig) return;
+ await onApiConfigChange?.({ ...provider.apiConfig, smallFastModel });
+ },
+ [canEdit, onApiConfigChange, provider.apiConfig],
+ );
const detect = useCallback(async () => {
// Remote platform agents (openclaw, hermes, …) have no local CLI to detect.
@@ -276,11 +332,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
command: resolvedCommand,
});
setStatus(result);
- if (result.available) {
- void fetchAuth();
- } else {
- setAuth(null);
- }
+ if (!result.available) setAuth(null);
} catch (error) {
console.error('[HeterogeneousAgentStatusCard] Failed to detect CLI:', error);
setStatus({ available: false, error: (error as Error).message });
@@ -288,12 +340,37 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
} finally {
setDetecting(false);
}
- }, [fetchAuth, provider.type, resolvedCommand]);
+ }, [provider.type, resolvedCommand]);
useEffect(() => {
void detect();
}, [detect]);
+ useEffect(() => {
+ if (provider.type !== 'claude-code' || authMode === 'api' || !status?.available) {
+ setAuth(null);
+ return;
+ }
+
+ // Keep the last subscription account visible while a redetect is in flight.
+ if (detecting) return;
+
+ let cancelled = false;
+ void (async () => {
+ try {
+ const result = await binaryService.getClaudeAuthStatus(resolvedCommand);
+ if (!cancelled) setAuth(result);
+ } catch (error) {
+ console.warn('[HeterogeneousAgentStatusCard] Failed to get Claude auth status:', error);
+ if (!cancelled) setAuth(null);
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [authMode, detecting, provider.type, resolvedCommand, status?.available]);
+
useEffect(() => {
setCommandInput(resolvedCommand);
}, [resolvedCommand]);
@@ -471,23 +548,72 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
);
};
- const renderAuth = () => {
- if (provider.type !== 'claude-code' || detecting || !status?.available || !auth?.loggedIn)
- return null;
+ const renderAuthMode = () => {
+ if (provider.type !== 'claude-code' || detecting || !status?.available) return null;
+ // Keep leftover API-mode agents visible so they can switch back; hide the
+ // experiment entirely for subscription agents until Labs is enabled.
+ if (!apiModeLabEnabled && authMode !== 'api') return null;
- const authMode =
- auth.authMethod === 'claude.ai' || auth.apiProvider === 'firstParty'
- ? t('heterogeneousStatus.auth.subscription')
- : t('heterogeneousStatus.auth.api');
+ const apiOptionEnabled = apiModeLabEnabled && apiModeAvailable;
+
+ return (
+ <div className={styles.detailRow}>
+ <Text className={styles.detailLabel}>{t('heterogeneousStatus.auth.label')}</Text>
+ <Flexbox horizontal align="center" gap={8} style={{ flexWrap: 'wrap' }}>
+ <Segmented
+ disabled={!canEdit}
+ size="small"
+ value={authMode}
+ options={[
+ {
+ label: t('heterogeneousStatus.auth.subscription'),
+ value: 'subscription',
+ },
+ {
+ disabled: !apiOptionEnabled,
+ label: t('heterogeneousStatus.auth.api'),
+ value: 'api',
+ },
+ ]}
+ onChange={(value) => {
+ void handleAuthModeChange(value as HeterogeneousAuthMode);
+ }}
+ />
+ {!apiModeLabEnabled ? (
+ <>
+ <Text className={styles.unavailableText}>
+ {t('heterogeneousStatus.apiMode.labDisabled')}
+ </Text>
+ <Text
+ className={styles.metaText}
+ style={{ cursor: 'pointer', textDecoration: 'underline' }}
+ onClick={() => navigate('/settings/labs')}
+ >
+ {t('heterogeneousStatus.apiMode.enableInLabs')}
+ </Text>
+ </>
+ ) : !apiModeAvailable ? (
+ <Text className={styles.unavailableText}>
+ {t('heterogeneousStatus.apiMode.localOnly')}
+ </Text>
+ ) : null}
+ </Flexbox>
+ </div>
+ );
+ };
+
+ const renderSubscriptionAccount = () => {
+ if (
+ provider.type !== 'claude-code' ||
+ authMode !== 'subscription' ||
+ detecting ||
+ !status?.available ||
+ !auth?.loggedIn
+ )
+ return null;
return (
<>
- <div className={styles.detailRow}>
- <Text className={styles.detailLabel}>{t('heterogeneousStatus.auth.label')}</Text>
- <Flexbox horizontal align="center" gap={8} style={{ flexWrap: 'wrap' }}>
- <Text className={styles.accountValue}>{authMode}</Text>
- </Flexbox>
- </div>
<div className={styles.detailRow}>
<Text className={styles.detailLabel}>{t('heterogeneousStatus.account.label')}</Text>
<Flexbox horizontal align="center" gap={8} style={{ flexWrap: 'wrap' }}>
@@ -510,6 +636,95 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
);
};
+ const renderApiConfig = () => {
+ if (
+ provider.type !== 'claude-code' ||
+ authMode !== 'api' ||
+ !apiModeLabEnabled ||
+ !apiModeAvailable ||
+ detecting ||
+ !status?.available
+ )
+ return null;
+
+ if (compatibleProviders.length === 0) {
+ return (
+ <div className={styles.detailRow}>
+ <Text className={styles.detailLabel}>{t('heterogeneousStatus.apiMode.model')}</Text>
+ <Flexbox horizontal align="center" gap={8} style={{ flexWrap: 'wrap' }}>
+ <Text className={styles.unavailableText}>
+ {t('heterogeneousStatus.apiMode.noProviders')}
+ </Text>
+ <Text
+ className={styles.metaText}
+ style={{ cursor: 'pointer', textDecoration: 'underline' }}
+ onClick={() => navigate('/settings/provider')}
+ >
+ {t('heterogeneousStatus.apiMode.configureProvider')}
+ </Text>
+ </Flexbox>
+ </div>
+ );
+ }
+
+ return (
+ <>
+ <div className={styles.detailRow}>
+ <Text className={styles.detailLabel}>{t('heterogeneousStatus.apiMode.model')}</Text>
+ <ModelSelect
+ initialWidth
+ disabled={!canEdit}
+ placeholder={t('heterogeneousStatus.apiMode.modelPlaceholder')}
+ popupWidth={360}
+ providerIds={compatibleProviderIds}
+ value={
+ provider.apiConfig
+ ? { model: provider.apiConfig.model, provider: provider.apiConfig.providerId }
+ : undefined
+ }
+ onChange={(value) => {
+ void handlePrimaryModelChange(value);
+ }}
+ />
+ </div>
+ {provider.apiConfig && (
+ <div className={styles.detailRow} style={{ alignItems: 'flex-start' }}>
+ <Text className={styles.detailLabel} style={{ paddingBlockStart: 14 }}>
+ {t('heterogeneousStatus.apiMode.smallFastModel')}
+ </Text>
+ <Flexbox gap={4} style={{ flex: 1, minWidth: 0 }}>
+ <ModelSelect
+ allowClear
+ initialWidth
+ disabled={!canEdit}
+ placeholder={t('heterogeneousStatus.apiMode.smallFastModelPlaceholder')}
+ popupWidth={360}
+ providerIds={[provider.apiConfig.providerId]}
+ value={
+ provider.apiConfig.smallFastModel
+ ? {
+ model: provider.apiConfig.smallFastModel,
+ provider: provider.apiConfig.providerId,
+ }
+ : undefined
+ }
+ onChange={({ model }) => {
+ void handleSmallFastModelChange(model);
+ }}
+ onClear={() => {
+ void handleSmallFastModelChange(null);
+ }}
+ />
+ <Text className={styles.metaText}>
+ {t('heterogeneousStatus.apiMode.smallFastModelDesc')}
+ </Text>
+ </Flexbox>
+ </div>
+ )}
+ </>
+ );
+ };
+
return (
<Flexbox className={styles.card} gap={12}>
<div className={styles.cardHeader}>
@@ -536,7 +751,9 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
</div>
<div className={styles.detailList}>
{renderCommandEditor()}
- {renderAuth()}
+ {renderAuthMode()}
+ {renderSubscriptionAccount()}
+ {renderApiConfig()}
</div>
{showCliInstallGuide && (
<HeterogeneousAgentStatusGuide
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
index 5a17a6b9625..ee0a979de16 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
@@ -2,6 +2,7 @@
import { isDesktop } from '@lobechat/const';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
+import type { HeterogeneousApiConfig, HeterogeneousAuthMode } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import type { TabsItem } from '@lobehub/ui/base-ui';
import { Tabs } from '@lobehub/ui/base-ui';
@@ -13,9 +14,13 @@ import { useTranslation } from 'react-i18next';
import ModelSelect from '@/features/ModelSelect';
import RunPriorityHint from '@/features/ProfileEditor/AgentUserTools/RunPriorityHint';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
import EditorCanvas from '../EditorCanvas';
import AgentHeader from './AgentHeader';
@@ -57,6 +62,8 @@ const ProfileEditor = memo(() => {
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const heterogeneousProvider = config?.agencyConfig?.heterogeneousProvider;
+ const { agencyConfig: effectiveAgencyConfig, workspaceScoped } =
+ useEffectiveAgencyConfig(agentId);
const updateHeterogeneousCommand = async (command: string) => {
if (!canEdit) return;
@@ -78,6 +85,24 @@ const ProfileEditor = memo(() => {
});
};
+ const updateHeterogeneousAuthMode = async (authMode: HeterogeneousAuthMode) => {
+ if (!canEdit || !heterogeneousProvider) return;
+ await updateAgentConfigById(agentId, {
+ agencyConfig: {
+ heterogeneousProvider: { ...heterogeneousProvider, authMode },
+ },
+ });
+ };
+
+ const updateHeterogeneousApiConfig = async (apiConfig: HeterogeneousApiConfig | undefined) => {
+ if (!canEdit || !heterogeneousProvider) return;
+ await updateAgentConfigById(agentId, {
+ agencyConfig: {
+ heterogeneousProvider: { ...heterogeneousProvider, apiConfig },
+ },
+ });
+ };
+
const updateBoundDeviceId = async (boundDeviceId: string) => {
await updateAgentConfigById(agentId, {
agencyConfig: { ...config?.agencyConfig, boundDeviceId, executionTarget: 'device' },
@@ -89,6 +114,14 @@ const ProfileEditor = memo(() => {
!!heterogeneousProvider &&
isRemoteHeterogeneousType(heterogeneousProvider.type);
const showCloudHeterogeneousTab = heterogeneousProvider?.type === 'claude-code';
+ const apiModeLabEnabled = useUserStore(labPreferSelectors.enableClaudeCodeApiMode);
+ const apiModeAvailable =
+ isDesktop &&
+ resolveExecutionTarget(effectiveAgencyConfig, {
+ clientExecutionAvailable: true,
+ isHetero: true,
+ workspaceScoped,
+ }) === 'local';
const heterogeneousTabItems: TabsItem[] = heterogeneousProvider
? [
...(showCloudHeterogeneousTab
@@ -111,7 +144,11 @@ const ProfileEditor = memo(() => {
disabled: !isDesktop,
children: (
<HeterogeneousAgentStatusCard
+ apiModeAvailable={apiModeAvailable}
+ apiModeLabEnabled={apiModeLabEnabled}
provider={heterogeneousProvider}
+ onApiConfigChange={updateHeterogeneousApiConfig}
+ onAuthModeChange={updateHeterogeneousAuthMode}
onCommandChange={updateHeterogeneousCommand}
/>
),
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts
index a205290876a..08707c3ae03 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts
@@ -3,6 +3,12 @@ import { describe, expect, it } from 'vitest';
import { selectRuntimeType } from '../dispatch/agentDispatcher';
const heteroProvider = { command: 'claude', type: 'claude-code' as const };
+const apiHeteroProvider = {
+ apiConfig: { model: 'claude-test', providerId: 'anthropic' },
+ authMode: 'api' as const,
+ command: 'claude',
+ type: 'claude-code' as const,
+};
const remoteHeteroProvider = { type: 'openclaw' as const };
const remoteHeteroProviderHermes = { type: 'hermes' as const };
@@ -78,6 +84,89 @@ describe('selectRuntimeType', () => {
});
describe('executionTarget routing for local CLI hetero', () => {
+ it('allows Claude Code API mode only for Desktop local execution', () => {
+ expect(
+ selectRuntimeType(
+ {
+ executionTarget: 'local',
+ heterogeneousProvider: apiHeteroProvider,
+ isGatewayMode: false,
+ },
+ { isDesktop: true },
+ ),
+ ).toBe('hetero');
+
+ expect(() =>
+ selectRuntimeType(
+ {
+ executionTarget: 'sandbox',
+ heterogeneousProvider: apiHeteroProvider,
+ isGatewayMode: false,
+ },
+ { isDesktop: true },
+ ),
+ ).toThrow(/Desktop local execution/);
+
+ expect(() =>
+ selectRuntimeType(
+ {
+ executionTarget: 'local',
+ heterogeneousProvider: apiHeteroProvider,
+ isGatewayMode: false,
+ },
+ { isDesktop: false },
+ ),
+ ).toThrow(/Desktop local execution/);
+ });
+
+ it.each(['client', 'gateway'] as const)(
+ 'rejects API mode inherited from the %s parent runtime',
+ (parentRuntime) => {
+ expect(() =>
+ selectRuntimeType(
+ {
+ executionTarget: 'local',
+ heterogeneousProvider: apiHeteroProvider,
+ isGatewayMode: false,
+ parentRuntime,
+ },
+ { isDesktop: true },
+ ),
+ ).toThrow(/Desktop local execution/);
+ },
+ );
+
+ it('allows API mode inherited from the Desktop hetero parent runtime', () => {
+ expect(
+ selectRuntimeType(
+ {
+ executionTarget: 'local',
+ heterogeneousProvider: apiHeteroProvider,
+ isGatewayMode: false,
+ parentRuntime: 'hetero',
+ },
+ { isDesktop: true },
+ ),
+ ).toBe('hetero');
+ });
+
+ it.each(['client', 'gateway', 'hetero'] as const)(
+ 'rejects every %s parent runtime for API mode on web',
+ (parentRuntime) => {
+ expect(() =>
+ selectRuntimeType(
+ {
+ executionTarget: 'local',
+ heterogeneousProvider: apiHeteroProvider,
+ isGatewayMode: false,
+ parentRuntime,
+ },
+ { isDesktop: false },
+ ),
+ ).toThrow(/Desktop local execution/);
+ },
+ );
+
it('routes to gateway when executionTarget = device on desktop', () => {
expect(
selectRuntimeType(
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index f1bb04e0cb4..a2eeb762989 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -21,6 +21,7 @@ import type { ChatTopicMetadata, HeterogeneousProviderConfig } from '@lobechat/t
import { ThreadStatus } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useAiInfraStore } from '@/store/aiInfra';
import { useChatStore } from '@/store/chat/store';
import { useUserStore } from '@/store/user';
@@ -598,6 +599,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
afterEach(() => {
vi.useRealTimers();
+ useAiInfraStore.setState({
+ aiProviderRuntimeConfig: {},
+ enabledAiModels: [],
+ enabledAiProviders: [],
+ });
delete (globalThis as any).window;
});
@@ -649,6 +655,157 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
return { get, store };
}
+ describe('Claude Code Desktop-local API binding', () => {
+ let previousLab: ReturnType<typeof useUserStore.getState>['preference']['lab'];
+
+ const setClaudeCodeApiModeLab = (enabled: boolean) => {
+ useUserStore.setState((state) => ({
+ preference: {
+ ...state.preference,
+ lab: { ...state.preference.lab, enableClaudeCodeApiMode: enabled },
+ },
+ }));
+ };
+
+ beforeEach(() => {
+ previousLab = useUserStore.getState().preference.lab;
+ setClaudeCodeApiModeLab(true);
+ });
+
+ afterEach(() => {
+ useUserStore.setState((state) => ({
+ preference: { ...state.preference, lab: previousLab },
+ }));
+ });
+
+ const apiProvider = {
+ apiConfig: { model: 'api-primary', providerId: 'anthropic-direct' },
+ args: ['--model', 'stale-arg-model', '--effort', 'high'],
+ authMode: 'api' as const,
+ command: 'claude',
+ env: {
+ ANTHROPIC_AUTH_TOKEN: 'stale-token',
+ CLAUDE_CODE_USE_BEDROCK: '1',
+ KEEP_ME: 'yes',
+ },
+ model: 'stale-config-model',
+ type: 'claude-code' as const,
+ };
+
+ const configureDirectProvider = () => {
+ useAiInfraStore.setState({
+ aiProviderRuntimeConfig: {
+ 'anthropic-direct': {
+ keyVaults: { apiKey: 'direct-key', baseURL: 'https://direct.example.com' },
+ settings: { sdkType: 'anthropic' },
+ } as any,
+ },
+ enabledAiModels: [
+ {
+ enabled: true,
+ id: 'api-primary',
+ providerId: 'anthropic-direct',
+ type: 'chat',
+ } as any,
+ ],
+ enabledAiProviders: [{ id: 'anthropic-direct' } as any],
+ });
+ };
+
+ it('launches with only the bound model and direct credentials', async () => {
+ configureDirectProvider();
+
+ await runWithEvents([ccResult()], {
+ params: { heterogeneousProvider: apiProvider },
+ });
+
+ expect(mockStartSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: ['--effort', 'high', '--model', 'api-primary'],
+ env: expect.objectContaining({
+ ANTHROPIC_AUTH_TOKEN: 'direct-key',
+ ANTHROPIC_BASE_URL: 'https://direct.example.com',
+ ANTHROPIC_MODEL: 'api-primary',
+ ANTHROPIC_SMALL_FAST_MODEL: 'api-primary',
+ CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST: '1',
+ CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: '1',
+ CLAUDE_CODE_USE_BEDROCK: '0',
+ CLAUDE_CODE_USE_MANTLE: '0',
+ CLAUDE_CODE_USE_VERTEX: '0',
+ KEEP_ME: 'yes',
+ }),
+ }),
+ );
+ const { env } = mockStartSession.mock.calls[0][0];
+ expect(env.ANTHROPIC_API_KEY).toBeUndefined();
+ expect(mockSelectAccountForAgent).not.toHaveBeenCalled();
+ expect(mockGetClaudeCodeIdentity).not.toHaveBeenCalled();
+ });
+
+ it('fails before spawn when the Labs experiment is disabled', async () => {
+ configureDirectProvider();
+ setClaudeCodeApiModeLab(false);
+ const store = createMockStore();
+
+ await executeHeterogeneousAgent(
+ vi.fn(() => store),
+ {
+ ...defaultParams,
+ heterogeneousProvider: apiProvider,
+ },
+ );
+
+ expect(mockStartSession).not.toHaveBeenCalled();
+ expect(mockUpdateMessageError).toHaveBeenCalledWith(
+ 'ast-initial',
+ expect.objectContaining({ message: expect.stringMatching(/labDisabled|Labs experiment/) }),
+ expect.anything(),
+ );
+ });
+
+ it('fails before spawn when the bound provider is disabled or deleted', async () => {
+ const store = createMockStore();
+
+ await executeHeterogeneousAgent(
+ vi.fn(() => store),
+ {
+ ...defaultParams,
+ heterogeneousProvider: apiProvider,
+ },
+ );
+
+ expect(mockStartSession).not.toHaveBeenCalled();
+ expect(mockUpdateMessageError).toHaveBeenCalledWith(
+ 'ast-initial',
+ expect.objectContaining({ message: expect.stringContaining('anthropic-direct') }),
+ expect.anything(),
+ );
+ });
+
+ it('fails before spawn when an explicitly bound fast model is unavailable', async () => {
+ configureDirectProvider();
+ const store = createMockStore();
+
+ await executeHeterogeneousAgent(
+ vi.fn(() => store),
+ {
+ ...defaultParams,
+ heterogeneousProvider: {
+ ...apiProvider,
+ apiConfig: { ...apiProvider.apiConfig, smallFastModel: 'disabled-fast-model' },
+ },
+ },
+ );
+
+ expect(mockStartSession).not.toHaveBeenCalled();
+ expect(mockUpdateMessageError).toHaveBeenCalledWith(
+ 'ast-initial',
+ expect.objectContaining({ message: expect.stringContaining('disabled-fast-model') }),
+ expect.anything(),
+ );
+ });
+ });
+
it('surfaces stream_retry metadata on the running operation and clears it on the next event', async () => {
const store = createMockStore();
const get = vi.fn(() => store);
diff --git a/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts b/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts
index af7ac82d014..9e01917d4a7 100644
--- a/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts
+++ b/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts
@@ -1,5 +1,8 @@
import { isDesktop as defaultIsDesktop } from '@lobechat/const';
-import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
+import {
+ CLAUDE_CODE_API_LOCAL_ONLY_ERROR,
+ isRemoteHeterogeneousType,
+} from '@lobechat/heterogeneous-agents';
import { type DeviceExecutionTarget, type HeterogeneousProviderConfig } from '@lobechat/types';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
@@ -103,6 +106,27 @@ export const selectRuntimeType = (
ctx: RuntimeSelectionContext,
{ isDesktop = defaultIsDesktop }: SelectRuntimeTypeOptions = {},
): AgentRuntimeType => {
+ if (
+ ctx.heterogeneousProvider?.type === 'claude-code' &&
+ ctx.heterogeneousProvider.authMode === 'api'
+ ) {
+ const target = resolveExecutionTarget(
+ {
+ boundDeviceId: ctx.boundDeviceId,
+ executionTarget: ctx.executionTarget,
+ heterogeneousProvider: ctx.heterogeneousProvider,
+ },
+ {
+ isHetero: true,
+ clientExecutionAvailable: isDesktop,
+ workspaceScoped: ctx.isWorkspaceAgent,
+ },
+ );
+ if (target !== 'local' || (ctx.parentRuntime && ctx.parentRuntime !== 'hetero')) {
+ throw new Error(CLAUDE_CODE_API_LOCAL_ONLY_ERROR);
+ }
+ }
+
if (ctx.parentRuntime) return ctx.parentRuntime;
// Notify-based platform agents (openclaw / hermes) use the gateway transport for both
// targets: `local` presets this desktop's personal device ID on the request, while
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 4255fcf5b70..0ff2d3fd794 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -6,6 +6,7 @@ import type {
import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
import {
+ buildClaudeCodeDirectEnv,
buildHeterogeneousAgentAuthRequiredError,
createMainAgentRunState,
isHeterogeneousAgentAuthRequired,
@@ -16,6 +17,8 @@ import {
reduceMainAgent,
rehydrateSubagentRunsState,
resolveHeterogeneousAgentCommand,
+ sanitizeClaudeCodeDirectArgs,
+ sanitizeClaudeCodeDirectEnv,
type SubagentIntent,
type SubagentRunSnapshot,
} from '@lobechat/heterogeneous-agents';
@@ -46,6 +49,7 @@ import { createNanoId } from '@lobechat/utils';
import { toast } from '@lobehub/ui/base-ui';
import { t } from 'i18next';
+import { validateClaudeCodeApiBinding } from '@/helpers/claudeCodeApiBinding';
import {
removeHeteroSessionIdForWorkingDirectory,
setHeteroSessionIdForWorkingDirectory,
@@ -59,6 +63,7 @@ import {
} from '@/services/message';
import { threadService } from '@/services/thread';
import { workService } from '@/services/work';
+import { getAiInfraStoreState } from '@/store/aiInfra';
import { topicSelectors } from '@/store/chat/selectors';
import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
import {
@@ -484,7 +489,7 @@ export const executeHeterogeneousAgent = async (
model?: string;
usage: unknown;
}) => {
- if (adapterType !== 'claude-code') return;
+ if (adapterType !== 'claude-code' || heterogeneousProvider.authMode === 'api') return;
const u = intent.usage as ModelUsage;
agentQuotaService
.recordUsage({
@@ -1798,11 +1803,78 @@ export const executeHeterogeneousAgent = async (
await rehydrateClientSubagentRuns();
+ let directEnv: Record<string, string> | undefined;
+ let directModel: string | undefined;
+ let spawnProvider = heterogeneousProvider;
+
+ if (adapterType === 'claude-code' && heterogeneousProvider.authMode === 'api') {
+ if (!labPreferSelectors.enableClaudeCodeApiMode(useUserStore.getState())) {
+ await persistTerminalError(
+ toHeterogeneousAgentMessageError(
+ new Error(t('heteroAgent.apiMode.labDisabled.title', { ns: 'chat' })),
+ adapterType,
+ ),
+ );
+ return;
+ }
+
+ const { apiConfig } = heterogeneousProvider;
+ const aiInfraState = getAiInfraStoreState();
+ const providerConfig = apiConfig
+ ? aiInfraState.aiProviderRuntimeConfig[apiConfig.providerId]
+ : undefined;
+ const bindingError = validateClaudeCodeApiBinding({
+ apiConfig,
+ enabledModels: aiInfraState.enabledAiModels ?? [],
+ providerEnabled:
+ !!apiConfig &&
+ !!providerConfig &&
+ !!aiInfraState.enabledAiProviders?.some((provider) => provider.id === apiConfig.providerId),
+ providerSdkType: providerConfig?.settings.sdkType,
+ });
+ if (bindingError) {
+ const message =
+ bindingError.code === 'configMissing'
+ ? t('heteroAgent.apiMode.configMissing', { ns: 'chat' })
+ : t(`heteroAgent.apiMode.${bindingError.code}`, {
+ ...bindingError,
+ ns: 'chat',
+ });
+ await persistTerminalError(toHeterogeneousAgentMessageError(new Error(message), adapterType));
+ return;
+ }
+
+ if (!apiConfig || !providerConfig) return;
+
+ const result = buildClaudeCodeDirectEnv({
+ keyVaults: providerConfig.keyVaults,
+ model: apiConfig.model,
+ sdkType: providerConfig.settings.sdkType,
+ smallFastModel: apiConfig.smallFastModel ?? undefined,
+ });
+ if (result.error) {
+ await persistTerminalError(
+ toHeterogeneousAgentMessageError(new Error(result.error), adapterType),
+ );
+ return;
+ }
+
+ directEnv = result.env;
+ directModel = apiConfig.model.trim();
+ spawnProvider = {
+ ...heterogeneousProvider,
+ args: sanitizeClaudeCodeDirectArgs(heterogeneousProvider.args),
+ model: undefined,
+ };
+ }
+
try {
// Account routing: realize the pinned/balanced account choice as spawn env
// (CLAUDE_CONFIG_DIR profile). Unbound agents get {} and spawn exactly as
// before; a quota-service failure must never block the run.
- const quotaAccountPlan = await resolveQuotaAccountSpawnPlan(context.agentId, adapterType);
+ const quotaAccountPlan = directEnv
+ ? { env: {}, externalAccountId: undefined }
+ : await resolveQuotaAccountSpawnPlan(context.agentId, adapterType);
const sessionEnv = {
// Tell the CLI which LobeHub conversation it is running inside. The child
@@ -1818,13 +1890,20 @@ export const executeHeterogeneousAgent = async (
...quotaAccountPlan.env,
// The agent's own env is the most specific choice and keeps winning —
// over both provenance and account routing.
- ...heterogeneousProvider.env,
+ ...(directEnv
+ ? sanitizeClaudeCodeDirectEnv(heterogeneousProvider.env)
+ : heterogeneousProvider.env),
+ ...directEnv,
};
+ const spawnArgs = buildHeteroSpawnArgs(spawnProvider);
+ const resolvedSpawnArgs =
+ directEnv && directModel ? [...(spawnArgs ?? []), '--model', directModel] : spawnArgs;
+
// Start session (pass resumeSessionId for multi-turn --resume)
const result = await heterogeneousAgentService.startSession({
agentType: adapterType,
- args: buildHeteroSpawnArgs(heterogeneousProvider),
+ args: resolvedSpawnArgs,
command: resolveHeterogeneousAgentCommand(adapterType, heterogeneousProvider.command),
cwd: workingDirectory,
env: sessionEnv,
@@ -1842,7 +1921,7 @@ export const executeHeterogeneousAgent = async (
// Attribute the run to the login the FINAL env actually resolves to (an
// agent-env CLAUDE_CONFIG_DIR beats routing, and unbound agents use the
// default login). Falls back to the routed choice when the file read fails.
- if (adapterType === 'claude-code') {
+ if (adapterType === 'claude-code' && !directEnv) {
heterogeneousAgentService
.getClaudeCodeIdentity({ env: sessionEnv })
.then((identity) => {
diff --git a/src/store/user/slices/preference/selectors.test.ts b/src/store/user/slices/preference/selectors.test.ts
index eace105c82a..3dcf079c270 100644
--- a/src/store/user/slices/preference/selectors.test.ts
+++ b/src/store/user/slices/preference/selectors.test.ts
@@ -114,6 +114,18 @@ describe('preferenceSelectors', () => {
expect(labPreferSelectors.enableMessageTextSelectionActions(store)).toBe(true);
});
+ it('keeps Claude Code API mode disabled by default', () => {
+ store.preference.lab = undefined;
+
+ expect(labPreferSelectors.enableClaudeCodeApiMode(store)).toBe(false);
+ });
+
+ it('returns the configured Claude Code API mode preference', () => {
+ store.preference.lab = { enableClaudeCodeApiMode: true };
+
+ expect(labPreferSelectors.enableClaudeCodeApiMode(store)).toBe(true);
+ });
+
it('keeps OAuth app management hidden by default', () => {
store.preference.lab = undefined;
diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.ts
index 8c19c12f9cc..7888c9b3782 100644
--- a/src/store/user/slices/preference/selectors/labPrefer.ts
+++ b/src/store/user/slices/preference/selectors/labPrefer.ts
@@ -9,6 +9,8 @@ export const labPreferSelectors = {
false,
enableArtifactDeployment: (s: UserState): boolean =>
s.preference.lab?.enableArtifactDeployment ?? false,
+ enableClaudeCodeApiMode: (s: UserState): boolean =>
+ s.preference.lab?.enableClaudeCodeApiMode ?? false,
enableClaudeCodeSdk: (s: UserState): boolean => s.preference.lab?.enableClaudeCodeSdk ?? false,
enableCodexAppServer: (s: UserState): boolean => s.preference.lab?.enableCodexAppServer ?? false,
enableDesktopSplitView: (s: UserState): boolean =>