🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(hetero): 为 Claude Code 助理增加可选的启动来源设置 (#22732)
Mochab1c804637f9a
diff --git a/apps/cli/src/commands/connect/handlers.ts b/apps/cli/src/commands/connect/handlers.tsindex 3fc39af1058..3491d305fee 100644--- a/apps/cli/src/commands/connect/handlers.ts+++ b/apps/cli/src/commands/connect/handlers.ts@@ -181,6 +181,7 @@ export function bindGatewayClientHandlers(assistantMessageId: request.assistantMessageId,args: request.args,claudeAccountRouting: request.claudeAccountRouting,+ claudeCodeEntrypoint: request.claudeCodeEntrypoint,cwd: request.cwd,imageList: request.imageList,jwt: request.jwt,diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.tsindex cea153fcc20..b317e60607e 100644--- a/apps/cli/src/device/agentRun.test.ts+++ b/apps/cli/src/device/agentRun.test.ts@@ -224,6 +224,77 @@ describe('spawnHeteroAgentRun', () => {);});+ it('runs Claude Code under the entrypoint the agent asked for', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);++ const ackPromise = spawnHeteroAgentRun({+ ...baseParams,+ agentType: 'claude-code',+ claudeCodeEntrypoint: 'lobehub',+ });+ child.emit('spawn');+ await ackPromise;++ const [, , opts] = spawnMock.mock.calls[0];+ expect(opts.env).toEqual(+ expect.objectContaining({+ CLAUDE_CODE_DISABLE_TERMINAL_TITLE: '1',+ CLAUDE_CODE_ENTRYPOINT: 'lobehub',+ }),+ );+ });++ // The value arrives from another machine and lands in a process environment.+ it('clears the entrypoint instead of passing on one that is not a plain name', async () => {+ vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', undefined);+ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);++ const ackPromise = spawnHeteroAgentRun({+ ...baseParams,+ agentType: 'claude-code',+ claudeCodeEntrypoint: 'x\nLD_PRELOAD=/tmp/evil.so',+ });+ child.emit('spawn');+ await ackPromise;++ const [, , opts] = spawnMock.mock.calls[0];+ expect(opts.env.CLAUDE_CODE_ENTRYPOINT).toBe('');+ });++ // An empty value reaches `lh hetero exec`, which removes the variable at spawn.+ it('clears an inherited entrypoint when the agent turned the setting off', async () => {+ vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', 'inherited');+ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);++ const ackPromise = spawnHeteroAgentRun({+ ...baseParams,+ agentType: 'claude-code',+ claudeCodeEntrypoint: '',+ });+ child.emit('spawn');+ await ackPromise;++ const [, , opts] = spawnMock.mock.calls[0];+ expect(opts.env.CLAUDE_CODE_ENTRYPOINT).toBe('');+ expect(opts.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE).toBeUndefined();+ });++ it('leaves an inherited entrypoint alone when the agent never set one', async () => {+ vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', 'inherited');+ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);++ const ackPromise = spawnHeteroAgentRun({ ...baseParams, agentType: 'claude-code' });+ child.emit('spawn');+ await ackPromise;++ const [, , opts] = spawnMock.mock.calls[0];+ expect(opts.env.CLAUDE_CODE_ENTRYPOINT).toBe('inherited');+ });+it('appends --resume when resuming a session', () => {const child = makeFakeChild();spawnMock.mockReturnValue(child);diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex d2eedfbcdad..4b95ee4fee4 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -5,6 +5,7 @@ import {resolveClaudeAccountSpawnEnv,} from '@lobechat/device-control/claude-code-account-routing';import {+ buildClaudeCodeEntrypointEnv,buildHeteroExecStdinPayload,HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,type HeteroExecImageRef,@@ -24,6 +25,8 @@ export interface SpawnHeteroAgentRunParams {assistantMessageId?: string;/** Claude Code account the server routed this run to. */claudeAccountRouting?: ClaudeCodeAccountRouting;+ /** Entrypoint name the agent asked Claude Code to report. */+ claudeCodeEntrypoint?: string;cwd?: string;/** Image attachments (signed URLs) appended as image content blocks. */imageList?: HeteroExecImageRef[];@@ -172,6 +175,9 @@ function startHeteroAgentRun(LOBEHUB_TOPIC_ID: topicId,...(workspaceId ? { LOBEHUB_WORKSPACE_ID: workspaceId } : {}),...accountEnv,+ ...(agentType === 'claude-code'+ ? buildClaudeCodeEntrypointEnv(params.claudeCodeEntrypoint)+ : {}),},stdio: ['pipe', 'inherit', 'inherit'],windowsHide: true,diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 2b0a5aa8346..31dee1c828f 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -78,7 +78,7 @@ import {ensureClaudeCodeResumeTranscript,findClaudeCodeTranscriptPath,getCodexAppServerUnsupportedArgs,- getHeterogeneousAgentPresetEnv,+ getHeterogeneousAgentSpawnEnv,prepareClaudeCodeLobeHubCli,readClaudeCodeSessionCost,readCodexSessionModel,@@ -947,10 +947,10 @@ export default class HeterogeneousAgentCtr {// shim finds its interpreter. `session.env` still wins if it sets PATH.if (session.resolvedCommandSearchPath) inheritedEnv.PATH = session.resolvedCommandSearchPath;const env: NodeJS.ProcessEnv = {- ...withEmbeddedCliEnv(inheritedEnv),- ...proxyEnv,- ...getHeterogeneousAgentPresetEnv(session.agentType),- ...session.env,+ ...getHeterogeneousAgentSpawnEnv(session.agentType, session.env, {+ ...withEmbeddedCliEnv(inheritedEnv),+ ...proxyEnv,+ }),...(includeProcessOwnership? managedProcessEnvironment({ ...session.processOwner, label: session.agentType },diff --git a/apps/desktop/src/main/controllers/gatewayAgentRun.ts b/apps/desktop/src/main/controllers/gatewayAgentRun.tsindex af456165ffa..d757c73205f 100644--- a/apps/desktop/src/main/controllers/gatewayAgentRun.ts+++ b/apps/desktop/src/main/controllers/gatewayAgentRun.ts@@ -2,6 +2,7 @@ import type { ChildProcess } from 'node:child_process';import { resolveClaudeAccountSpawnEnv } from '@lobechat/device-control/claude-code-account-routing';import type { AgentRunRequestMessage } from '@lobechat/device-gateway-client';+import { buildClaudeCodeEntrypointEnv } from '@lobechat/heterogeneous-agents/protocol';import type HeterogeneousAgentCtr from './HeterogeneousAgentCtr';@@ -84,7 +85,12 @@ export const executeGatewayAgentRun = async (// the process has actually spawned (or emitted an early error) before// acknowledging the server request.return await heterogeneousAgentCtr.spawnLhHeteroExec({- accountEnv: account.env,+ accountEnv: {+ ...account.env,+ ...(request.agentType === 'claude-code'+ ? buildClaudeCodeEntrypointEnv(request.claudeCodeEntrypoint)+ : {}),+ },agentId: request.agentId,agentType: request.agentType,assistantMessageId: request.assistantMessageId,diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.tsindex 0ba52852b2d..16481488675 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts@@ -4,6 +4,7 @@ import {appendAttachedFilesToPrompt,collectHeteroAttachedFiles,isLocalHeterogeneousType,+ resolveDispatchedClaudeCodeEntrypoint,} from '@lobechat/heterogeneous-agents';import {CHANNEL_INSTRUCTIONS,@@ -279,6 +280,13 @@ export const prepareHeteroRun = async (const heteroParams = {agentType: heteroType,assistantMessageId,+ // The one setting that travels from the agent's env to wherever the run+ // lands: forwarding the whole env would let an agent's author set arbitrary+ // variables on a member's device.+ claudeCodeEntrypoint:+ heteroType === 'claude-code' && heterogeneousProvider?.type === heteroType+ ? resolveDispatchedClaudeCodeEntrypoint(heterogeneousProvider.env)+ : undefined,githubToken,imageList: heteroImageList,jwt: operationJwt,diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.tsindex fe1fde70f85..398dfc694dd 100644--- a/apps/server/src/services/deviceGateway/agents.ts+++ b/apps/server/src/services/deviceGateway/agents.ts@@ -160,6 +160,8 @@ export async function dispatchAgentRun(args?: string[];/** Claude Code account the device must spawn on; see the request message. */claudeAccountRouting?: ClaudeCodeAccountRouting;+ /** Entrypoint name the agent asked Claude Code to report; see the request message. */+ claudeCodeEntrypoint?: string;/** Restricts the run to connections of these clients; omitted means any client. */clientKinds?: DeviceClient[];cwd?: string;diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.tsindex ea7123904bc..abf281ecc63 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts@@ -170,4 +170,53 @@ describe('spawnHeteroSandbox', () => {const command = mockCallTool.mock.calls[0][1].command;expect(command).toContain("LOBEHUB_WORKSPACE_ID='ws-lobehub'");});++ it('runs Claude Code under the entrypoint the agent asked for', async () => {+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ assistantMessageId: 'msg-1',+ claudeCodeEntrypoint: 'lobehub',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ const command = mockCallTool.mock.calls[0][1].command;+ expect(command).toContain("CLAUDE_CODE_ENTRYPOINT='lobehub'");+ expect(command).toContain("CLAUDE_CODE_DISABLE_TERMINAL_TITLE='1'");+ });++ it('leaves the entrypoint to Claude Code unless the agent set one', async () => {+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ assistantMessageId: 'msg-1',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(mockCallTool.mock.calls[0][1].command).not.toContain('CLAUDE_CODE_ENTRYPOINT');+ });++ it('clears the entrypoint when the agent turned the setting off', async () => {+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ assistantMessageId: 'msg-1',+ claudeCodeEntrypoint: '',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(mockCallTool.mock.calls[0][1].command).toContain("CLAUDE_CODE_ENTRYPOINT=''");+ });});diff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.tsindex a48687c39b9..81f28f6247f 100644--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts@@ -4,6 +4,7 @@// repo source tree into every serverless function (250 MB limit blowout).import { isPersistentSandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';import {+ buildClaudeCodeEntrypointEnv,buildHeteroExecStdinPayload,type HeteroExecImageRef,} from '@lobechat/heterogeneous-agents/protocol';@@ -26,6 +27,8 @@ export interface SandboxRunParams {* the CLI can pass it through the heteroIngest payload, removing the need for the server* to re-read topic.metadata.runningOperation on every cold Lambda start. */assistantMessageId: string;+ /** Entrypoint name the agent asked Claude Code to report instead of its headless default. */+ claudeCodeEntrypoint?: string;cwd?: string;/** GitHub OAuth token for cloning private repos. */githubToken?: string;@@ -228,6 +231,11 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<void// Inject GitHub token so CC can authenticate git operations and GitHub API// calls inside the sandbox (e.g. gh CLI, git push, API requests)....(githubToken ? [`GITHUB_TOKEN=${shellQuote(githubToken)}`] : []),+ ...(agentType === 'claude-code'+ ? Object.entries(buildClaudeCodeEntrypointEnv(params.claudeCodeEntrypoint)).map(+ ([key, value]) => `${key}=${shellQuote(value)}`,+ )+ : []),].join(' ');const shellArgs = args.map(shellQuote).join(' ');const mainCommand = `echo ${shellQuote(base64Payload)} | base64 -d | ${envVars} ${shellArgs}`;diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 19187cec174..899152cf217 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1004,6 +1004,10 @@"heterogeneousStatus.device.scanFailedTag": "Unknown","heterogeneousStatus.device.showDetails": "Show details","heterogeneousStatus.device.unavailable": "{{name}} CLI not found on {{device}}",+ "heterogeneousStatus.entrypoint.desc": "Tell Claude Code that it is launched by {{name}}, to avoid the doubled usage that unattended runs are charged.",+ "heterogeneousStatus.entrypoint.label": "Launch Source",+ "heterogeneousStatus.entrypoint.risk": "High risk: this changes how the client identifies itself to Anthropic. We can't tell how Anthropic monitors it, and your account may be restricted or banned. Turn it on at your own risk.",+ "heterogeneousStatus.entrypoint.switch": "Report a custom launch source","heterogeneousStatus.plan.label": "Plan","heterogeneousStatus.redetect": "Re-detect","heterogeneousStatus.runtime.bundled": "dsh CLI",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex ab8405d2165..c207883d289 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1004,6 +1004,10 @@"heterogeneousStatus.device.scanFailedTag": "无法检测","heterogeneousStatus.device.showDetails": "查看详情","heterogeneousStatus.device.unavailable": "未在 {{device}} 上检测到 {{name}} CLI",+ "heterogeneousStatus.entrypoint.desc": "让 Claude Code 以「由 {{name}} 启动」的身份运行,以规避无人值守调用的双倍用量消耗。",+ "heterogeneousStatus.entrypoint.label": "启动来源",+ "heterogeneousStatus.entrypoint.risk": "高风险:这会改变客户端向 Anthropic 表明的身份。我们无法判断 Anthropic 的监测策略,账号可能因此被限制或封禁,请自行评估后再开启。",+ "heterogeneousStatus.entrypoint.switch": "上报自定义启动来源","heterogeneousStatus.plan.label": "方案","heterogeneousStatus.redetect": "重新检测","heterogeneousStatus.runtime.bundled": "dsh CLI",diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex 41e44fbd6ec..2ed4c689937 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -319,6 +319,7 @@ export class GatewayHttpClient {/** Resolved `lh hetero exec` wrapper args. */args?: string[];claudeAccountRouting?: AgentRunRequestMessage['claudeAccountRouting'];+ claudeCodeEntrypoint?: string;/** Restricts the run to connections of these clients; omitted means any client. */clientKinds?: DeviceClient[];cwd?: string;diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex ca533788445..e544f273f61 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -270,6 +270,14 @@ export interface AgentRunRequestMessage {candidates: Array<{ externalAccountId: string; name?: string }>;mode: 'balanced' | 'pinned';};+ /**+ * Entrypoint name the agent asked Claude Code to report instead of its+ * headless default. The device validates it and sets it on the spawned CLI.+ * An empty string means the agent turned the setting off, so the device+ * clears an entrypoint it inherited. Optional — omitted when the agent never+ * set it; an older device ignores it.+ */+ claudeCodeEntrypoint?: string;cwd?: string;/*** Image attachments from the user message, as URLs the device can fetchdiff --git a/packages/heterogeneous-agents/src/claudeCodeEntrypoint.ts b/packages/heterogeneous-agents/src/claudeCodeEntrypoint.tsnew file mode 100644index 00000000000..e64a8111b40--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodeEntrypoint.ts@@ -0,0 +1,53 @@+export const CLAUDE_CODE_ENTRYPOINT_ENV = 'CLAUDE_CODE_ENTRYPOINT';+export const DEFAULT_CLAUDE_CODE_ENTRYPOINT = 'lobehub';++const ENTRYPOINT_PATTERN = /^[\w.-]{1,64}$/;++/**+ * The entrypoint name an agent may report, or `undefined` when unset or not a+ * plain identifier. A dispatched run carries this value to another machine,+ * so anything else is dropped instead of reaching a process environment.+ */+export const normalizeClaudeCodeEntrypoint = (value: unknown): string | undefined => {+ if (typeof value !== 'string') return;+ const entrypoint = value.trim();+ return ENTRYPOINT_PATTERN.test(entrypoint) ? entrypoint : undefined;+};++/**+ * What a dispatched run carries for the agent's setting: the name, an empty+ * string when the agent turned it off (so the receiving host clears one it+ * inherited), or `undefined` when the agent never set it.+ */+export const resolveDispatchedClaudeCodeEntrypoint = (+ agentEnv: Readonly<Record<string, string>> | undefined,+): string | undefined => {+ const value = agentEnv?.[CLAUDE_CODE_ENTRYPOINT_ENV];+ return value === undefined ? undefined : (normalizeClaudeCodeEntrypoint(value) ?? '');+};++/**+ * Env a host adds for a dispatched Claude Code run. A name is reported as the+ * entrypoint; headless Claude Code reports `sdk-cli`, and under any other+ * entrypoint it spends an extra model request naming a terminal title nothing+ * reads, so that is turned off. Any other string clears the variable: it is+ * set empty here and removed where the CLI is spawned.+ */+export const buildClaudeCodeEntrypointEnv = (value: unknown): Record<string, string> => {+ if (typeof value !== 'string') return {};+ const entrypoint = normalizeClaudeCodeEntrypoint(value);+ if (!entrypoint) return { [CLAUDE_CODE_ENTRYPOINT_ENV]: '' };+ return { CLAUDE_CODE_DISABLE_TERMINAL_TITLE: '1', [CLAUDE_CODE_ENTRYPOINT_ENV]: entrypoint };+};++/**+ * Removes an entrypoint the agent cleared. Agent config saves merge, so a+ * turned-off setting is stored as an empty value; passing that on would hand+ * Claude Code an empty entrypoint instead of letting it report its own.+ */+export const dropClearedClaudeCodeEntrypoint = <T extends Record<string, string | undefined>>(+ env: T,+): T => {+ if (env[CLAUDE_CODE_ENTRYPOINT_ENV]?.trim() === '') delete env[CLAUDE_CODE_ENTRYPOINT_ENV];+ return env;+};diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex 47d411035e0..9bc09f518e0 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -12,6 +12,13 @@ export {collectHeteroAttachedFiles,type HeteroAttachedFileRef,} from './attachedFiles';+export {+ buildClaudeCodeEntrypointEnv,+ CLAUDE_CODE_ENTRYPOINT_ENV,+ DEFAULT_CLAUDE_CODE_ENTRYPOINT,+ normalizeClaudeCodeEntrypoint,+ resolveDispatchedClaudeCodeEntrypoint,+} from './claudeCodeEntrypoint';export type {HeterogeneousAgentCliError,HeterogeneousAgentDescriptor,diff --git a/packages/heterogeneous-agents/src/protocol/index.ts b/packages/heterogeneous-agents/src/protocol/index.tsindex b83421d784c..2003a1ea0d9 100644--- a/packages/heterogeneous-agents/src/protocol/index.ts+++ b/packages/heterogeneous-agents/src/protocol/index.ts@@ -1,3 +1,9 @@+export {+ buildClaudeCodeEntrypointEnv,+ CLAUDE_CODE_ENTRYPOINT_ENV,+ DEFAULT_CLAUDE_CODE_ENTRYPOINT,+ normalizeClaudeCodeEntrypoint,+} from '../claudeCodeEntrypoint';/*** Wire contract between hetero dispatch sites and the executing* `lh hetero exec` CLI. Pure and isomorphic — no fs, no process, no node-onlydiff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex 8742520b066..085dddd7ddb 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -208,7 +208,7 @@ export {findClaudeCodeTranscriptPath,resolveClaudeCodeTranscriptPath,} from './ensureResumeTranscript';-export { getHeterogeneousAgentPresetEnv } from './presetEnv';+export { getHeterogeneousAgentSpawnEnv } from './presetEnv';export {AMP_BASE_ARGS,buildQoderArgs,diff --git a/packages/heterogeneous-agents/src/spawn/presetEnv.ts b/packages/heterogeneous-agents/src/spawn/presetEnv.tsindex e19145e566d..d974c57a0a5 100644--- a/packages/heterogeneous-agents/src/spawn/presetEnv.ts+++ b/packages/heterogeneous-agents/src/spawn/presetEnv.ts@@ -1,3 +1,8 @@+import {+ CLAUDE_CODE_ENTRYPOINT_ENV,+ dropClearedClaudeCodeEntrypoint,+} from '../claudeCodeEntrypoint';+/*** Environment variables a host always sets for a heterogeneous agent, shared by* every spawn site (desktop CLI/SDK runs, `lh hetero exec`). Hosts apply them@@ -18,6 +23,35 @@ const HETEROGENEOUS_AGENT_PRESET_ENV: Partial<Record<string, Readonly<Record<str'codebuddy': { CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS: '1' },};-export const getHeterogeneousAgentPresetEnv = (+/**+ * @param agentEnv the agent's configured `env`, which the host applies over+ * the result. Presets that only make sense next to a setting the agent chose+ * are derived from it.+ */+const getHeterogeneousAgentPresetEnv = (+ agentType: string,+ agentEnv?: Readonly<Record<string, string | undefined>>,+): Readonly<Record<string, string>> => {+ const preset = HETEROGENEOUS_AGENT_PRESET_ENV[agentType] ?? {};+ // An agent that picks its own entrypoint also gets the terminal title off.+ if (agentType === 'claude-code' && agentEnv?.[CLAUDE_CODE_ENTRYPOINT_ENV]?.trim()) {+ return { ...preset, CLAUDE_CODE_DISABLE_TERMINAL_TITLE: '1' };+ }+ return preset;+};++/**+ * The environment a host spawns a run with: what it inherited, then the+ * presets, then the agent's own `env` on top. An entrypoint the agent cleared+ * is removed from the result, so an inherited one does not stand in for it.+ */+export const getHeterogeneousAgentSpawnEnv = <T extends Record<string, string | undefined>>(agentType: string,-): Readonly<Record<string, string>> => HETEROGENEOUS_AGENT_PRESET_ENV[agentType] ?? {};+ agentEnv?: Readonly<Record<string, string>>,+ inheritedEnv?: T,+): T =>+ dropClearedClaudeCodeEntrypoint({+ ...inheritedEnv,+ ...getHeterogeneousAgentPresetEnv(agentType, agentEnv),+ ...agentEnv,+ } as T);diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.presetEnv.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.presetEnv.test.tsindex 4c50e74bb07..c9f156536b5 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.presetEnv.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.presetEnv.test.ts@@ -66,6 +66,46 @@ describe('spawnAgent preset env', () => {expect(env.MCP_CONNECTION_NONBLOCKING).toBe('true');});+ it('leaves the entrypoint and terminal title to Claude Code by default', async () => {+ vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', undefined);+ vi.stubEnv('CLAUDE_CODE_DISABLE_TERMINAL_TITLE', undefined);++ const env = await spawnClaudeCode();++ expect(env.CLAUDE_CODE_ENTRYPOINT).toBeUndefined();+ expect(env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE).toBeUndefined();+ });++ // A non-default entrypoint makes Claude Code spend a request on a terminal title.+ it('turns off terminal titles for an agent that sets its own entrypoint', async () => {+ vi.stubEnv('CLAUDE_CODE_DISABLE_TERMINAL_TITLE', undefined);++ const env = await spawnClaudeCode({ CLAUDE_CODE_ENTRYPOINT: 'lobehub' });++ expect(env.CLAUDE_CODE_ENTRYPOINT).toBe('lobehub');+ expect(env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE).toBe('1');+ });++ // Turned off means no custom entrypoint, even one the launcher inherited.+ it('does not pass on an entrypoint the agent cleared', async () => {+ vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', 'inherited');+ vi.stubEnv('CLAUDE_CODE_DISABLE_TERMINAL_TITLE', undefined);++ const env = await spawnClaudeCode({ CLAUDE_CODE_ENTRYPOINT: '' });++ expect('CLAUDE_CODE_ENTRYPOINT' in env).toBe(false);+ expect(env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE).toBeUndefined();+ });++ it('keeps an agent-configured terminal title setting', async () => {+ const env = await spawnClaudeCode({+ CLAUDE_CODE_DISABLE_TERMINAL_TITLE: '0',+ CLAUDE_CODE_ENTRYPOINT: 'lobehub',+ });++ expect(env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE).toBe('0');+ });+it('does not apply the Claude Code preset to other agents', async () => {vi.stubEnv('MCP_CONNECTION_NONBLOCKING', undefined);diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 9418353bfe4..93c09b2ccec 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -28,7 +28,7 @@ import {import type { AgentPromptInput, BuildAgentInputOptions } from './input';import { buildAgentInput } from './input';import { prepareClaudeCodeLobeHubCli } from './lobeHubCliPlugin';-import { getHeterogeneousAgentPresetEnv } from './presetEnv';+import { getHeterogeneousAgentSpawnEnv } from './presetEnv';import { assertSpawnableWorkingDirectory } from './workingDirectory';export interface SpawnAgentOptions {@@ -506,11 +506,11 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentoptions.inputOptions,);const inputPlan = { ...promptPlan, args: [...lobeHubCli.args, ...promptPlan.args] };- const childEnv: NodeJS.ProcessEnv = {- ...process.env,- ...getHeterogeneousAgentPresetEnv(options.agentType),- ...options.env,- };+ const childEnv: NodeJS.ProcessEnv = getHeterogeneousAgentSpawnEnv(+ options.agentType,+ options.env,+ process.env,+ );// Codex builds each shell command's env from `[shell_environment_policy]`,// not from its own process env, so a user's `inherit = "core"` strips the// run context `lh` needs. Forward it as `shell_environment_policy.set.*`diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 13c6e4c4e2a..ea3e6bc93c5 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -553,6 +553,12 @@ export default {'heterogeneousStatus.command.label': 'Launch Command','heterogeneousStatus.command.placeholder': 'Command name or absolute path','heterogeneousStatus.detecting': 'Detecting {{name}} CLI...',+ 'heterogeneousStatus.entrypoint.desc':+ 'Tell Claude Code that it is launched by {{name}}, to avoid the doubled usage that unattended runs are charged.',+ 'heterogeneousStatus.entrypoint.label': 'Launch Source',+ 'heterogeneousStatus.entrypoint.risk':+ "High risk: this changes how the client identifies itself to Anthropic. We can't tell how Anthropic monitors it, and your account may be restricted or banned. Turn it on at your own risk.",+ 'heterogeneousStatus.entrypoint.switch': 'Report a custom launch source','heterogeneousStatus.plan.label': 'Plan','heterogeneousStatus.redetect': 'Re-detect','heterogeneousStatus.unavailable': '{{name}} CLI not found. Please install or configure it.',diff --git a/src/features/HeterogeneousAgent/ClaudeCodeEntrypointSetting.test.tsx b/src/features/HeterogeneousAgent/ClaudeCodeEntrypointSetting.test.tsxnew file mode 100644index 00000000000..2178bc6387e--- /dev/null+++ b/src/features/HeterogeneousAgent/ClaudeCodeEntrypointSetting.test.tsx@@ -0,0 +1,110 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { ClaudeCodeEntrypointSetting } from './ClaudeCodeEntrypointSetting';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { name?: string }) =>+ key === 'heterogeneousStatus.entrypoint.desc' ? `Launched by ${options?.name}` : key,+ }),+}));++const SWITCH = 'heterogeneousStatus.entrypoint.switch';+const RISK = 'heterogeneousStatus.entrypoint.risk';++describe('ClaudeCodeEntrypointSetting', () => {+ it('is off by default, warns about the risk and writes lobehub when turned on', async () => {+ const onEnvChange = vi.fn();+ render(+ <ClaudeCodeEntrypointSetting+ env={{ ANTHROPIC_BASE_URL: 'https://example.com' }}+ onEnvChange={onEnvChange}+ />,+ );++ const toggle = screen.getByRole('switch', { name: SWITCH });+ expect(toggle).not.toBeChecked();+ expect(screen.getByText(RISK)).toBeInTheDocument();++ fireEvent.click(toggle);++ await waitFor(() => {+ expect(onEnvChange).toHaveBeenCalledWith({+ ANTHROPIC_BASE_URL: 'https://example.com',+ CLAUDE_CODE_ENTRYPOINT: 'lobehub',+ });+ });+ });++ it('describes the name being typed and saves it', async () => {+ const onEnvChange = vi.fn();+ render(+ <ClaudeCodeEntrypointSetting+ env={{ CLAUDE_CODE_ENTRYPOINT: 'lobehub' }}+ onEnvChange={onEnvChange}+ />,+ );++ const input = screen.getByDisplayValue('lobehub');+ expect(screen.getByText('Launched by lobehub')).toBeInTheDocument();++ fireEvent.change(input, { target: { value: ' my-app ' } });+ expect(screen.getByText('Launched by my-app')).toBeInTheDocument();+ fireEvent.blur(input);++ await waitFor(() => {+ expect(onEnvChange).toHaveBeenCalledWith({ CLAUDE_CODE_ENTRYPOINT: 'my-app' });+ });+ });++ it('falls back to lobehub when cleared and keeps the saved name for an unusable one', async () => {+ const onEnvChange = vi.fn();+ render(+ <ClaudeCodeEntrypointSetting+ env={{ CLAUDE_CODE_ENTRYPOINT: 'my-app' }}+ onEnvChange={onEnvChange}+ />,+ );++ const input = screen.getByDisplayValue('my-app');+ fireEvent.change(input, { target: { value: 'a b; rm -rf' } });+ fireEvent.blur(input);++ expect(input).toHaveValue('my-app');+ expect(onEnvChange).not.toHaveBeenCalled();++ fireEvent.change(input, { target: { value: '' } });+ fireEvent.blur(input);++ await waitFor(() => {+ expect(onEnvChange).toHaveBeenCalledWith({ CLAUDE_CODE_ENTRYPOINT: 'lobehub' });+ });+ });++ // Saves merge into the stored env, so a missing key would keep the old value.+ it('clears the entrypoint with an empty value when turned off', async () => {+ const onEnvChange = vi.fn();+ render(+ <ClaudeCodeEntrypointSetting+ env={{ ANTHROPIC_BASE_URL: 'https://example.com', CLAUDE_CODE_ENTRYPOINT: 'my-app' }}+ onEnvChange={onEnvChange}+ />,+ );++ fireEvent.click(screen.getByRole('switch', { name: SWITCH }));++ await waitFor(() => {+ expect(onEnvChange).toHaveBeenCalledWith({+ ANTHROPIC_BASE_URL: 'https://example.com',+ CLAUDE_CODE_ENTRYPOINT: '',+ });+ });+ });++ it('reads a cleared entrypoint as off', () => {+ render(<ClaudeCodeEntrypointSetting env={{ CLAUDE_CODE_ENTRYPOINT: '' }} />);++ expect(screen.getByRole('switch', { name: SWITCH })).not.toBeChecked();+ });+});diff --git a/src/features/HeterogeneousAgent/ClaudeCodeEntrypointSetting.tsx b/src/features/HeterogeneousAgent/ClaudeCodeEntrypointSetting.tsxnew file mode 100644index 00000000000..05b828d2a98--- /dev/null+++ b/src/features/HeterogeneousAgent/ClaudeCodeEntrypointSetting.tsx@@ -0,0 +1,131 @@+'use client';++import {+ CLAUDE_CODE_ENTRYPOINT_ENV,+ DEFAULT_CLAUDE_CODE_ENTRYPOINT,+ normalizeClaudeCodeEntrypoint,+} from '@lobechat/heterogeneous-agents';+import { Flexbox, Input, Switch, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++const styles = stylex.create({+ hint: {+ color: cssVar.colorTextSecondary,+ fontSize: 12,+ lineHeight: '18px',+ },+ input: {+ fontFamily: cssVar.fontFamilyCode,+ width: 'min(200px, 100%)',+ },+ risk: {+ color: cssVar.colorWarning,+ fontSize: 12,+ lineHeight: '18px',+ },+ switchLine: {+ minHeight: 28,+ },+});++interface ClaudeCodeEntrypointSettingProps {+ disabled?: boolean;+ /** The agent's configured env; the entrypoint is one variable in it. */+ env?: Record<string, string>;+ onEnvChange?: (env: Record<string, string>) => Promise<void> | void;+}++/**+ * Lets a Claude Code agent report its own launch source. Off clears the+ * variable, so Claude Code reports its headless default.+ */+export const ClaudeCodeEntrypointSetting = memo<ClaudeCodeEntrypointSettingProps>(+ ({ disabled, env, onEnvChange }) => {+ const { t } = useTranslation('setting');+ const entrypoint = normalizeClaudeCodeEntrypoint(env?.[CLAUDE_CODE_ENTRYPOINT_ENV]);+ // Text being typed; `undefined` shows the saved entrypoint.+ const [draft, setDraft] = useState<string>();+ const [saving, setSaving] = useState(false);++ const save = async (next: string | undefined) => {+ if (disabled || saving || next === entrypoint) return;++ try {+ setSaving(true);+ // Agent config saves merge into the stored env, so a dropped key would+ // survive: an empty value is how a variable is cleared.+ await onEnvChange?.({ ...env, [CLAUDE_CODE_ENTRYPOINT_ENV]: next ?? '' });+ } finally {+ setSaving(false);+ }+ };++ const commitDraft = () => {+ if (draft === undefined) return;+ setDraft(undefined);+ // Cleared falls back to the default; a name that cannot be used keeps the saved one.+ void save(+ draft.trim()+ ? (normalizeClaudeCodeEntrypoint(draft) ?? entrypoint)+ : DEFAULT_CLAUDE_CODE_ENTRYPOINT,+ );+ };++ return (+ <Flexbox gap={6}>+ <Flexbox horizontal align="center" gap={8} wrap="wrap" {...stylex.props(styles.switchLine)}>+ <Switch+ aria-label={t('heterogeneousStatus.entrypoint.switch')}+ checked={!!entrypoint}+ disabled={disabled}+ loading={saving}+ size="small"+ onChange={(checked) => {+ void save(checked ? DEFAULT_CLAUDE_CODE_ENTRYPOINT : undefined);+ }}+ />+ {entrypoint && (+ <Input+ aria-label={t('heterogeneousStatus.entrypoint.label')}+ disabled={disabled || saving}+ maxLength={64}+ placeholder={DEFAULT_CLAUDE_CODE_ENTRYPOINT}+ size="small"+ value={draft ?? entrypoint}+ onBlur={commitDraft}+ onChange={(event) => {+ setDraft(event.target.value);+ }}+ onKeyDown={(event) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ setDraft(undefined);+ return;+ }++ if (event.key === 'Enter') {+ event.preventDefault();+ commitDraft();+ }+ }}+ {...stylex.props(styles.input)}+ />+ )}+ </Flexbox>+ <Text {...stylex.props(styles.hint)}>+ {t('heterogeneousStatus.entrypoint.desc', {+ interpolation: { escapeValue: false },+ name:+ normalizeClaudeCodeEntrypoint(draft) ?? entrypoint ?? DEFAULT_CLAUDE_CODE_ENTRYPOINT,+ })}+ </Text>+ <Text {...stylex.props(styles.risk)}>{t('heterogeneousStatus.entrypoint.risk')}</Text>+ </Flexbox>+ );+ },+);++ClaudeCodeEntrypointSetting.displayName = 'ClaudeCodeEntrypointSetting';diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsxindex 6454ce72d6c..af4ec05692f 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx@@ -10,13 +10,14 @@ import {import type { HeterogeneousApiConfig, HeterogeneousAuthMode } from '@lobechat/types';import { Alert, Button, createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';import isEqual from 'fast-deep-equal';-import { ChevronDown, MonitorSmartphone, Wrench } from 'lucide-react';+import { ChevronDown, Fingerprint, MonitorSmartphone, Wrench } from 'lucide-react';import React, { memo } from 'react';import { useTranslation } from 'react-i18next';import { AGENT_SHARE_ALLOWED_PROVIDERS } from '@/business/agent-share';import { useAgentShareSupported } from '@/business/client/useAgentShareSupported';import { ModelIcon } from '@/components/LobeIcons';+import { ClaudeCodeEntrypointSetting } from '@/features/HeterogeneousAgent/ClaudeCodeEntrypointSetting';import { ApiAuthLocalOnlyNotice } from '@/features/HeterogeneousAgent/ExecutionEnvironment/ApiAuthLocalOnlyNotice';import { DeviceCliStatusCard } from '@/features/HeterogeneousAgent/ExecutionEnvironment/DeviceCliStatusCard';import { HeteroExecutionTargetSelect } from '@/features/HeterogeneousAgent/ExecutionEnvironment/HeteroExecutionTargetSelect';@@ -302,6 +303,21 @@ const ProfileEditor = memo(() => {/></WorkspaceAgentPolicyCard>{renderHeterogeneousPanel()}+ {/* Follows the engine and its sign-in, not where the run lands. */}+ {heterogeneousProvider.type === 'claude-code' &&+ (heterogeneousProvider.authMode ?? 'subscription') === 'subscription' && (+ <WorkspaceAgentPolicyCard+ fullWidth+ icon={Fingerprint}+ title={t('heterogeneousStatus.entrypoint.label')}+ >+ <ClaudeCodeEntrypointSetting+ disabled={!canEdit}+ env={heterogeneousProvider.env}+ onEnvChange={updateHeterogeneousEnv}+ />+ </WorkspaceAgentPolicyCard>+ )}</>) : isWorkspaceAgent ? (<>