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.

πŸ› fix(agent-quota): route device-bound Claude Code runs to the selected account (#21604)

Arvin Xu7605d74a9bc0
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index d0a30a11053..6f0d46fe77b 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -1139,6 +1139,7 @@ function bindGatewayClientHandlers(
agentType: request.agentType,
assistantMessageId: request.assistantMessageId,
args: request.args,
+ claudeAccountRouting: request.claudeAccountRouting,
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.ts
index b972073fc88..bbcf92a3e39 100644
--- a/apps/cli/src/device/agentRun.test.ts
+++ b/apps/cli/src/device/agentRun.test.ts
@@ -16,8 +16,17 @@ const { saveTaskMock, getTaskMock, removeTaskMock } = vi.hoisted(() => ({
removeTaskMock: vi.fn(),
saveTaskMock: vi.fn(),
}));
+const { identityMock, hasLoginMock } = vi.hoisted(() => ({
+ hasLoginMock: vi.fn(),
+ identityMock: vi.fn(),
+}));
vi.mock('node:child_process', () => ({ spawn: spawnMock }));
+// The device's own Claude Code login, read for account routing.
+vi.mock('@lobechat/heterogeneous-agents/quota-sampler', () => ({
+ hasClaudeCodeLogin: hasLoginMock,
+ readClaudeCodeIdentity: identityMock,
+}));
vi.mock('../daemon/taskRegistry', () => ({
getTask: getTaskMock,
removeTask: removeTaskMock,
@@ -401,3 +410,43 @@ describe('spawnHeteroAgentRun', () => {
expect(removeTaskMock).not.toHaveBeenCalled();
});
});
+
+describe('spawnHeteroAgentRun Claude Code account routing', () => {
+ beforeEach(() => {
+ vi.mocked(statSync).mockReturnValue(asDirectory);
+ identityMock.mockResolvedValue({ externalAccountId: 'acc-default' });
+ hasLoginMock.mockResolvedValue(true);
+ });
+
+ afterEach(() => {
+ spawnMock.mockReset();
+ });
+
+ it('rejects a run pinned to an account this device is not signed in to', async () => {
+ const result = await spawnHeteroAgentRun({
+ ...baseParams,
+ claudeAccountRouting: {
+ candidates: [{ externalAccountId: 'acc-other', name: '[email protected]' }],
+ mode: 'pinned',
+ },
+ });
+
+ expect(result.status).toBe('rejected');
+ expect(result.reason).toContain('[email protected]');
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it('runs a run pinned to the account this device is signed in to', async () => {
+ const child = makeFakeChild();
+ spawnMock.mockReturnValue(child);
+
+ const pending = spawnHeteroAgentRun({
+ ...baseParams,
+ claudeAccountRouting: { candidates: [{ externalAccountId: 'acc-default' }], mode: 'pinned' },
+ });
+ await vi.waitFor(() => expect(spawnMock).toHaveBeenCalled());
+ child.emit('spawn');
+
+ expect(await pending).toEqual({ status: 'accepted' });
+ });
+});
diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.ts
index 1e796d405b8..660a6247dfe 100644
--- a/apps/cli/src/device/agentRun.ts
+++ b/apps/cli/src/device/agentRun.ts
@@ -1,11 +1,16 @@
import { spawn } from 'node:child_process';
+import {
+ listDefaultClaudeLogin,
+ resolveClaudeAccountSpawnEnv,
+} from '@lobechat/device-control/claude-code-account-routing';
import {
buildHeteroExecStdinPayload,
HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,
type HeteroExecImageRef,
stripInheritedRunIdentity,
} from '@lobechat/heterogeneous-agents/protocol';
+import type { ClaudeCodeAccountRouting } from '@lobechat/heterogeneous-agents/quota';
import { resolveHeteroSpawnCwd } from '@lobechat/heterogeneous-agents/workingDirectory';
import { getTask, removeTask, saveTask } from '../daemon/taskRegistry';
@@ -17,6 +22,8 @@ export interface SpawnHeteroAgentRunParams {
/** Resolved `lh hetero exec` wrapper args. */
args?: string[];
assistantMessageId?: string;
+ /** Claude Code account the server routed this run to. */
+ claudeAccountRouting?: ClaudeCodeAccountRouting;
cwd?: string;
/** Image attachments (signed URLs) appended as image content blocks. */
imageList?: HeteroExecImageRef[];
@@ -61,6 +68,26 @@ interface SpawnHeteroAgentRunLogger {
export function spawnHeteroAgentRun(
params: SpawnHeteroAgentRunParams,
logger?: SpawnHeteroAgentRunLogger,
+): Promise<AgentRunAckResult> {
+ if (!params.claudeAccountRouting) return startHeteroAgentRun(params, {}, logger);
+
+ // A plain CLI device holds one Claude Code login (the one `claude` uses
+ // here), so routing either confirms it or rejects a run pinned elsewhere.
+ const inheritedEnv = stripInheritedRunIdentity(process.env);
+ return resolveClaudeAccountSpawnEnv(params.claudeAccountRouting, {
+ inheritedEnv,
+ listLogins: () => listDefaultClaudeLogin(inheritedEnv),
+ }).then((account) => {
+ if (account.kind === 'spawn') return startHeteroAgentRun(params, account.env, logger);
+ logger?.error?.(`hetero exec rejected (op=${params.operationId}): ${account.reason}`);
+ return { reason: account.reason, status: 'rejected' as const };
+ });
+}
+
+function startHeteroAgentRun(
+ params: SpawnHeteroAgentRunParams,
+ accountEnv: Record<string, string>,
+ logger?: SpawnHeteroAgentRunLogger,
): Promise<AgentRunAckResult> {
const {
agentType,
@@ -144,6 +171,7 @@ export function spawnHeteroAgentRun(
LOBEHUB_SERVER: serverUrl,
LOBEHUB_TOPIC_ID: topicId,
...(workspaceId ? { LOBEHUB_WORKSPACE_ID: workspaceId } : {}),
+ ...accountEnv,
},
stdio: ['pipe', 'inherit', 'inherit'],
windowsHide: true,
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 630a84b3415..5acc9497c53 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -1,4 +1,4 @@
-import { type ChildProcess, execFileSync, spawn } from 'node:child_process';
+import { execFileSync, spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -8,7 +8,7 @@ import {
COMPUTER_USE_IDENTIFIER as AuvIdentifier,
toAuvToolOutput,
} from '@lobechat/device-control/computer-use';
-import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';
+import type { GatewayMcpParams } from '@lobechat/device-gateway-client';
import { deviceGatewayServerKey } from '@lobechat/device-gateway-client/endpoint';
import type {
GatewayConnectionState,
@@ -40,6 +40,7 @@ import { createLogger } from '@/utils/logger';
import { setDesktopUserAgentHeader } from '@/utils/user-agent';
import BrowserControlCtr from './BrowserControlCtr';
+import { executeGatewayAgentRun, type PlatformTaskEntry } from './gatewayAgentRun';
import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';
import { ControllerModule, createProtocolHandler, IpcMethod } from './index';
import LocalFileCtr from './LocalFileCtr';
@@ -105,20 +106,6 @@ function buildNotifyProtocol(lhPath: string, topicId: string): string {
);
}
-interface PlatformTaskEntry {
- agentId?: string;
- agentType: string;
- operationId: string;
- parentOperationId?: string;
- pid: number;
- topicId: string;
- /**
- * Workspace owning the dispatched topic (seeded by `runHeteroTask`), so the
- * exit-time cleanup notify scopes to the workspace agentNotify resolves it in.
- */
- workspaceId?: string;
-}
-
/**
* Local mirror of `@lobechat/types`' `BuiltinServerRuntimeOutput`. Inlined
* because the desktop tsconfig doesn't expose `@lobechat/types`, and the shape
@@ -225,7 +212,14 @@ export default class GatewayConnectionCtr extends ControllerModule {
);
// Wire up agent run handler
- srv.setAgentRunHandler((request) => this.executeAgentRun(request));
+ srv.setAgentRunHandler((request) =>
+ executeGatewayAgentRun(request, {
+ getAccessToken: () => this.remoteServerConfigCtr.getAccessToken(),
+ getServerUrl: () => this.remoteServerConfigCtr.getRemoteServerUrl(),
+ heterogeneousAgentCtr: this.heterogeneousAgentCtr,
+ platformTasks: this.platformTasks,
+ }),
+ );
// Wire up generic device RPC handler (server-internal method forwarding,
// e.g. workspace-init scans β€” never surfaced to the agent)
@@ -363,80 +357,6 @@ export default class GatewayConnectionCtr extends ControllerModule {
// ─── Agent Run Routing ───
- private async executeAgentRun(
- request: AgentRunRequestMessage,
- ): Promise<{ reason?: string; status: 'accepted' | 'rejected' }> {
- try {
- const serverUrl = await this.remoteServerConfigCtr.getRemoteServerUrl();
- if (!serverUrl) {
- return { reason: 'Remote server URL not configured', status: 'rejected' };
- }
-
- // Reuse this device's own logged-in session as the run identity. The
- // access token is a full user OIDC token (7-day TTL, longer than any run),
- // which heteroIngest/heteroFinish now accept (ownership-gated), AND which
- // gives the spawned Claude Code's nested `lh` calls a real login state β€”
- // unlike the narrow `hetero-operation` token, which only works for the
- // ingest endpoints. We deliberately do NOT pass the refresh token to the
- // CLI: the device stays the single refresher (refresh tokens rotate), and
- // the 7-day access token outlives the run so no mid-run refresh is needed.
- //
- // Fall back to the dispatched `request.jwt` when the device has no access
- // token (e.g. not logged in), preserving the prior behavior gracefully.
- const accessToken = await this.remoteServerConfigCtr.getAccessToken();
- const jwt = accessToken || request.jwt;
-
- // The embedded CLI handles spawn -> adapt -> BatchIngester ->
- // heteroIngest/heteroFinish -> server -> Gateway -> clients. Wait until
- // the process has actually spawned (or emitted an early error) before
- // acknowledging the server request.
- return await this.heterogeneousAgentCtr.spawnLhHeteroExec({
- agentId: request.agentId,
- agentType: request.agentType,
- assistantMessageId: request.assistantMessageId,
- args: request.args,
- cwd: request.cwd,
- imageList: request.imageList,
- jwt,
- operationId: request.operationId,
- prompt: request.prompt,
- resumeFallbackSystemContext: request.resumeFallbackSystemContext,
- resumeSessionId: request.resumeSessionId,
- serverUrl,
- systemContext: request.systemContext,
- topicId: request.topicId,
- workspaceId: request.ingestWorkspaceId ?? request.workspaceId,
- // Register the spawned CLI process so `cancelHeteroTask` (sent by the
- // server's `interruptTask` when the user clicks Stop) can find and kill
- // it by operationId. The entry is cleaned up on child exit below.
- onChildSpawned: (child: ChildProcess) => {
- const pid = child.pid;
- if (pid === undefined) return;
- const taskId = request.operationId;
- this.platformTasks.set(taskId, {
- agentType: request.agentType,
- operationId: request.operationId,
- pid,
- topicId: request.topicId,
- workspaceId: request.ingestWorkspaceId ?? request.workspaceId,
- });
- child.once('exit', () => {
- // Only clear if this exit belongs to the current entry β€” a
- // superseding run for the same operationId may have already
- // replaced it.
- const current = this.platformTasks.get(taskId);
- if (current?.pid === pid) {
- this.platformTasks.delete(taskId);
- }
- });
- },
- });
- } catch (err) {
- const reason = err instanceof Error ? err.message : String(err);
- return { reason, status: 'rejected' };
- }
- }
-
// ─── Tool Call Routing ───
/**
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 4794175534d..621c607c910 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -47,7 +47,6 @@ import type {
import {
buildHeteroExecStdinPayload,
buildHeterogeneousPrompt,
- HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,
stripInheritedRunIdentity,
} from '@lobechat/heterogeneous-agents/protocol';
import {
@@ -147,6 +146,7 @@ import {
HeteroInflightRunRegistry,
} from '@/modules/heterogeneousAgent/inflightRunRegistry';
import { fetchKimiCodeQuota } from '@/modules/heterogeneousAgent/kimiCodeQuota';
+import { buildLhHeteroExecEnv } from '@/modules/heterogeneousAgent/lhHeteroExecEnv';
import { PiRpcPool } from '@/modules/heterogeneousAgent/piRpcPool';
import type { HostedProviderBinding } from '@/modules/heterogeneousAgent/providerBindingHost';
import {
@@ -4075,6 +4075,8 @@ export default class HeterogeneousAgentCtr {
* eager accepted ack would strand the server operation without a producer.
*/
spawnLhHeteroExec(params: {
+ /** Account-routing env (`CLAUDE_CONFIG_DIR` of the routed login), if any. */
+ accountEnv?: Record<string, string>;
agentId?: string;
agentType: string;
assistantMessageId?: string;
@@ -4102,20 +4104,16 @@ export default class HeterogeneousAgentCtr {
}): Promise<{ reason?: string; status: 'accepted' | 'rejected' }> {
const {
agentType,
- assistantMessageId,
args: extraArgs,
cwd,
imageList,
- jwt,
operationId,
onChildSpawned,
prompt,
resumeFallbackSystemContext,
resumeSessionId,
- serverUrl,
systemContext,
topicId,
- workspaceId,
} = params;
const workDir = cwd ?? process.cwd();
// Let the embedded CLI classify a stale project path and finish the
@@ -4170,25 +4168,10 @@ export default class HeterogeneousAgentCtr {
});
}
- // Never inherit the launcher's run identity (or JWT file) for a dispatched run.
- const childEnv = stripInheritedRunIdentity(process.env);
-
- const env = {
- ...withEmbeddedCliEnv(childEnv),
- ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
- ELECTRON_RUN_AS_NODE: '1',
- [HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV]: '1',
- ...(params.agentId ? { LOBEHUB_AGENT_ID: params.agentId } : {}),
- LOBEHUB_JWT: jwt,
- LOBEHUB_OPERATION_ID: operationId,
- LOBEHUB_TOPIC_ID: topicId,
- ...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),
- LOBEHUB_SERVER: serverUrl,
- // Same reason `runHeteroTask` injects this for notify: without it the
- // CLI's heteroIngest/heteroFinish fall back to personal scope and the
- // workspace topic 404s (empty assistant, topic stuck `running`).
- ...(workspaceId ? { LOBEHUB_WORKSPACE_ID: workspaceId } : {}),
- };
+ const env = buildLhHeteroExecEnv({
+ ...params,
+ proxyEnv: buildProxyEnv(this.app.storeManager.get('networkProxy')),
+ });
logger.info('spawnLhHeteroExec: type=%s op=%s topic=%s', agentType, operationId, topicId);
diff --git a/apps/desktop/src/main/controllers/__tests__/gatewayAgentRun.test.ts b/apps/desktop/src/main/controllers/__tests__/gatewayAgentRun.test.ts
new file mode 100644
index 00000000000..8cb6ef6af37
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/gatewayAgentRun.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { executeGatewayAgentRun, type GatewayAgentRunDeps } from '../gatewayAgentRun';
+
+const createDeps = (ctr: Partial<GatewayAgentRunDeps['heterogeneousAgentCtr']> = {}) =>
+ ({
+ getAccessToken: vi.fn().mockResolvedValue('access-token'),
+ getServerUrl: vi.fn().mockResolvedValue('https://app.lobehub.com'),
+ heterogeneousAgentCtr: {
+ getClaudeCodeInheritedRoutingEnv: vi.fn().mockResolvedValue({}),
+ listClaudeCodeAccounts: vi.fn().mockResolvedValue([]),
+ resolveClaudeCodeAccount: vi.fn().mockResolvedValue({ kind: 'missing' }),
+ spawnLhHeteroExec: vi.fn().mockResolvedValue({ status: 'accepted' }),
+ ...ctr,
+ },
+ platformTasks: new Map(),
+ }) as unknown as GatewayAgentRunDeps;
+
+const request = (extra: Record<string, unknown> = {}) =>
+ ({
+ agentType: 'claude-code',
+ jwt: 'dispatch-jwt',
+ operationId: 'op-1',
+ prompt: 'hi',
+ topicId: 'topic-1',
+ type: 'agent_run_request',
+ ...extra,
+ }) as Parameters<typeof executeGatewayAgentRun>[0];
+
+describe('executeGatewayAgentRun Claude Code account routing', () => {
+ it('spawns an unrouted run without reading the local logins', async () => {
+ const deps = createDeps();
+
+ expect(await executeGatewayAgentRun(request(), deps)).toEqual({ status: 'accepted' });
+ expect(deps.heterogeneousAgentCtr.listClaudeCodeAccounts).not.toHaveBeenCalled();
+ expect(deps.heterogeneousAgentCtr.spawnLhHeteroExec).toHaveBeenCalledWith(
+ expect.objectContaining({ accountEnv: {}, jwt: 'access-token' }),
+ );
+ });
+
+ it('spawns a routed run on the profile of its account', async () => {
+ const deps = createDeps({
+ listClaudeCodeAccounts: vi.fn().mockResolvedValue([
+ { configDir: null, identity: { externalAccountId: 'acc-default' } },
+ { configDir: '/profiles/acc-pinned', identity: { externalAccountId: 'acc-pinned' } },
+ ]),
+ resolveClaudeCodeAccount: vi
+ .fn()
+ .mockResolvedValue({ configDir: '/profiles/acc-pinned', kind: 'profile' }),
+ });
+
+ await executeGatewayAgentRun(
+ request({
+ claudeAccountRouting: { candidates: [{ externalAccountId: 'acc-pinned' }], mode: 'pinned' },
+ }),
+ deps,
+ );
+
+ expect(deps.heterogeneousAgentCtr.spawnLhHeteroExec).toHaveBeenCalledWith(
+ expect.objectContaining({ accountEnv: { CLAUDE_CONFIG_DIR: '/profiles/acc-pinned' } }),
+ );
+ });
+
+ it('rejects a run pinned to an account this desktop is not signed in to', async () => {
+ const deps = createDeps({
+ listClaudeCodeAccounts: vi
+ .fn()
+ .mockResolvedValue([{ configDir: null, identity: { externalAccountId: 'acc-default' } }]),
+ });
+
+ const ack = await executeGatewayAgentRun(
+ request({
+ claudeAccountRouting: {
+ candidates: [{ externalAccountId: 'acc-pinned', name: '[email protected]' }],
+ mode: 'pinned',
+ },
+ }),
+ deps,
+ );
+
+ expect(ack).toEqual({
+ reason: expect.stringContaining('[email protected]'),
+ status: 'rejected',
+ });
+ expect(deps.heterogeneousAgentCtr.spawnLhHeteroExec).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/controllers/gatewayAgentRun.ts b/apps/desktop/src/main/controllers/gatewayAgentRun.ts
new file mode 100644
index 00000000000..7cf4726e9bb
--- /dev/null
+++ b/apps/desktop/src/main/controllers/gatewayAgentRun.ts
@@ -0,0 +1,139 @@
+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 type HeterogeneousAgentCtr from './HeterogeneousAgentCtr';
+
+export interface PlatformTaskEntry {
+ agentId?: string;
+ agentType: string;
+ operationId: string;
+ parentOperationId?: string;
+ pid: number;
+ topicId: string;
+ /**
+ * Workspace owning the dispatched topic (seeded by `runHeteroTask`), so the
+ * exit-time cleanup notify scopes to the workspace agentNotify resolves it in.
+ */
+ workspaceId?: string;
+}
+
+export interface GatewayAgentRunDeps {
+ getAccessToken: () => Promise<string | null | undefined>;
+ getServerUrl: () => Promise<string | undefined>;
+ heterogeneousAgentCtr: Pick<
+ HeterogeneousAgentCtr,
+ | 'getClaudeCodeInheritedRoutingEnv'
+ | 'listClaudeCodeAccounts'
+ | 'resolveClaudeCodeAccount'
+ | 'spawnLhHeteroExec'
+ >;
+ /** Gateway-run processes by operationId, so `cancelHeteroTask` can kill them. */
+ platformTasks: Map<string, PlatformTaskEntry>;
+}
+
+export interface GatewayAgentRunAck {
+ reason?: string;
+ status: 'accepted' | 'rejected';
+}
+
+/**
+ * The Claude Code account the agent is routed to, as spawn env: its login on
+ * this desktop (default, or a profile signed in from Manage accounts).
+ */
+const resolveClaudeAccountEnv = async (
+ ctr: GatewayAgentRunDeps['heterogeneousAgentCtr'],
+ request: AgentRunRequestMessage,
+) =>
+ resolveClaudeAccountSpawnEnv(request.claudeAccountRouting, {
+ inheritedEnv: request.claudeAccountRouting
+ ? await ctr.getClaudeCodeInheritedRoutingEnv().catch(() => ({}))
+ : {},
+ listLogins: () => ctr.listClaudeCodeAccounts(),
+ prepareLogin: (externalAccountId) => ctr.resolveClaudeCodeAccount({ externalAccountId }),
+ });
+
+/**
+ * Run a gateway-dispatched agent on this desktop by spawning the embedded
+ * `lh hetero exec`, and acknowledge with the spawn outcome.
+ */
+export const executeGatewayAgentRun = async (
+ request: AgentRunRequestMessage,
+ deps: GatewayAgentRunDeps,
+): Promise<GatewayAgentRunAck> => {
+ const { heterogeneousAgentCtr, platformTasks } = deps;
+ try {
+ const serverUrl = await deps.getServerUrl();
+ if (!serverUrl) {
+ return { reason: 'Remote server URL not configured', status: 'rejected' };
+ }
+
+ // Reuse this device's own logged-in session as the run identity. The
+ // access token is a full user OIDC token (7-day TTL, longer than any run),
+ // which heteroIngest/heteroFinish now accept (ownership-gated), AND which
+ // gives the spawned Claude Code's nested `lh` calls a real login state β€”
+ // unlike the narrow `hetero-operation` token, which only works for the
+ // ingest endpoints. We deliberately do NOT pass the refresh token to the
+ // CLI: the device stays the single refresher (refresh tokens rotate), and
+ // the 7-day access token outlives the run so no mid-run refresh is needed.
+ //
+ // Fall back to the dispatched `request.jwt` when the device has no access
+ // token (e.g. not logged in), preserving the prior behavior gracefully.
+ const accessToken = await deps.getAccessToken();
+ const jwt = accessToken || request.jwt;
+
+ const account = await resolveClaudeAccountEnv(heterogeneousAgentCtr, request);
+ if (account.kind === 'reject') return { reason: account.reason, status: 'rejected' };
+
+ // The embedded CLI handles spawn -> adapt -> BatchIngester ->
+ // heteroIngest/heteroFinish -> server -> Gateway -> clients. Wait until
+ // the process has actually spawned (or emitted an early error) before
+ // acknowledging the server request.
+ return await heterogeneousAgentCtr.spawnLhHeteroExec({
+ accountEnv: account.env,
+ agentId: request.agentId,
+ agentType: request.agentType,
+ assistantMessageId: request.assistantMessageId,
+ args: request.args,
+ cwd: request.cwd,
+ imageList: request.imageList,
+ jwt,
+ operationId: request.operationId,
+ prompt: request.prompt,
+ resumeFallbackSystemContext: request.resumeFallbackSystemContext,
+ resumeSessionId: request.resumeSessionId,
+ serverUrl,
+ systemContext: request.systemContext,
+ topicId: request.topicId,
+ workspaceId: request.ingestWorkspaceId ?? request.workspaceId,
+ // Register the spawned CLI process so `cancelHeteroTask` (sent by the
+ // server's `interruptTask` when the user clicks Stop) can find and kill
+ // it by operationId. The entry is cleaned up on child exit below.
+ onChildSpawned: (child: ChildProcess) => {
+ const pid = child.pid;
+ if (pid === undefined) return;
+ const taskId = request.operationId;
+ platformTasks.set(taskId, {
+ agentType: request.agentType,
+ operationId: request.operationId,
+ pid,
+ topicId: request.topicId,
+ workspaceId: request.ingestWorkspaceId ?? request.workspaceId,
+ });
+ child.once('exit', () => {
+ // Only clear if this exit belongs to the current entry β€” a
+ // superseding run for the same operationId may have already
+ // replaced it.
+ const current = platformTasks.get(taskId);
+ if (current?.pid === pid) {
+ platformTasks.delete(taskId);
+ }
+ });
+ },
+ });
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ return { reason, status: 'rejected' };
+ }
+};
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/lhHeteroExecEnv.ts b/apps/desktop/src/main/modules/heterogeneousAgent/lhHeteroExecEnv.ts
new file mode 100644
index 00000000000..ce0f9054fd4
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/lhHeteroExecEnv.ts
@@ -0,0 +1,41 @@
+import {
+ HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,
+ stripInheritedRunIdentity,
+} from '@lobechat/heterogeneous-agents/protocol';
+
+import { withEmbeddedCliEnv } from '@/modules/cliEmbedding';
+
+export interface LhHeteroExecEnvParams {
+ /** Account-routing env (`CLAUDE_CONFIG_DIR` of the routed login), if any. */
+ accountEnv?: Record<string, string>;
+ agentId?: string;
+ assistantMessageId?: string;
+ jwt: string;
+ operationId: string;
+ /** Network-proxy env from the desktop settings. */
+ proxyEnv: Record<string, string>;
+ serverUrl: string;
+ topicId: string;
+ /** Topic/run workspace β€” forwarded as `LOBEHUB_WORKSPACE_ID` for ingest. */
+ workspaceId?: string;
+}
+
+/** Env for the embedded `lh hetero exec` a gateway-dispatched run spawns. */
+export const buildLhHeteroExecEnv = (params: LhHeteroExecEnvParams) => ({
+ // Never inherit the launcher's run identity (or JWT file) for a dispatched run.
+ ...withEmbeddedCliEnv(stripInheritedRunIdentity(process.env)),
+ ...params.proxyEnv,
+ ELECTRON_RUN_AS_NODE: '1',
+ [HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV]: '1',
+ ...(params.agentId ? { LOBEHUB_AGENT_ID: params.agentId } : {}),
+ LOBEHUB_JWT: params.jwt,
+ LOBEHUB_OPERATION_ID: params.operationId,
+ LOBEHUB_TOPIC_ID: params.topicId,
+ ...(params.assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: params.assistantMessageId } : {}),
+ LOBEHUB_SERVER: params.serverUrl,
+ // Same reason `runHeteroTask` injects this for notify: without it the
+ // CLI's heteroIngest/heteroFinish fall back to personal scope and the
+ // workspace topic 404s (empty assistant, topic stuck `running`).
+ ...(params.workspaceId ? { LOBEHUB_WORKSPACE_ID: params.workspaceId } : {}),
+ ...params.accountEnv,
+});
diff --git a/apps/server/src/services/agentQuota/__tests__/index.test.ts b/apps/server/src/services/agentQuota/__tests__/index.test.ts
index 38ed865022a..15645ab1ef8 100644
--- a/apps/server/src/services/agentQuota/__tests__/index.test.ts
+++ b/apps/server/src/services/agentQuota/__tests__/index.test.ts
@@ -229,6 +229,65 @@ describe('AgentQuotaService.selectForAgent', () => {
});
});
+describe('AgentQuotaService.planDeviceRouting', () => {
+ const now = Date.parse('2026-07-02T00:00:00Z');
+ const weekly = (utilization: number) => ({
+ capturedAt: now - 60_000,
+ limitType: 'weekly_all',
+ resetsAt: now + 3 * 24 * HOUR,
+ scopeKey: '',
+ utilization,
+ });
+
+ it('sends a pin as the only candidate, and the pool best-first otherwise', async () => {
+ const bindings = new AgentAccountBindingModel(serverDB, userId);
+ await serverDB.insert(agents).values([{ id: 'agent-d', slug: 'agent-d', title: 'D', userId }]);
+ const busy = await service.ingestSnapshot({
+ identity: { email: '[email protected]', externalAccountId: 'busy-acc' },
+ provider: 'claude-code',
+ readings: [weekly(80)],
+ });
+ const free = await service.ingestSnapshot({
+ identity: { email: '[email protected]', externalAccountId: 'free-acc' },
+ provider: 'claude-code',
+ readings: [weekly(10)],
+ });
+ const spent = await service.ingestSnapshot({
+ identity: { externalAccountId: 'spent-acc' },
+ provider: 'claude-code',
+ readings: [weekly(100)],
+ });
+
+ expect(await service.planDeviceRouting('agent-d', { now, provider: 'claude-code' })).toBeNull();
+
+ for (const account of [busy, free, spent])
+ await bindings.upsert({
+ accountId: account.id,
+ agentId: 'agent-d',
+ role: QuotaBindingRole.pool,
+ });
+
+ // An exhausted account is not a candidate; the rest go most headroom first.
+ expect(await service.planDeviceRouting('agent-d', { now, provider: 'claude-code' })).toEqual({
+ candidates: [
+ { externalAccountId: 'free-acc', name: '[email protected]' },
+ { externalAccountId: 'busy-acc', name: '[email protected]' },
+ ],
+ mode: 'balanced',
+ });
+
+ await bindings.upsert({
+ accountId: busy.id,
+ agentId: 'agent-d',
+ role: QuotaBindingRole.pinned,
+ });
+ expect(await service.planDeviceRouting('agent-d', { now, provider: 'claude-code' })).toEqual({
+ candidates: [{ externalAccountId: 'busy-acc', name: '[email protected]' }],
+ mode: 'pinned',
+ });
+ });
+});
+
describe('AgentQuotaService.listLatestReadings', () => {
const now = Date.parse('2026-07-02T00:00:00Z');
const weeklyReading = {
diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.ts
index b937e5948f5..8d577aa88ce 100644
--- a/apps/server/src/services/agentQuota/index.ts
+++ b/apps/server/src/services/agentQuota/index.ts
@@ -1,6 +1,8 @@
import {
type AccountLoad,
calibrateCapacity,
+ type ClaudeCodeAccountRouting,
+ type ClaudeCodeRoutedAccount,
computeTurnCostUsd,
currentUtilization,
isScopedWeeklyLimit,
@@ -12,6 +14,7 @@ import {
type QuotaAccountIdentity,
type QuotaLimitReading,
type QuotaTokenUsage,
+ rankAccounts,
selectAccount,
windowSecondsForKind,
windowsToCalibrationIntervals,
@@ -31,6 +34,7 @@ import {
type QuotaAccountCredentialRef,
QuotaBindingRole,
QuotaCostSource,
+ QuotaCredentialMode,
} from '@/database/types/agentQuota';
import { claudeModelPrice, codexModelPrice } from './pricing';
@@ -468,21 +472,71 @@ export class AgentQuotaService {
};
};
+ /**
+ * The account choice for a run on an execution device, which picks the
+ * login itself (only it knows which accounts it is signed in to): the pin,
+ * or the whole eligible pool best-first. `null` = no routing, and the device
+ * spawns on its default login as before.
+ *
+ * Only `referenced` accounts map to a device login; a run pinned to any
+ * other account keeps the default login, as on the desktop.
+ */
+ planDeviceRouting = async (
+ agentId: string,
+ options: Pick<SelectAccountOptions, 'modelScope' | 'now' | 'provider'> = {},
+ ): Promise<ClaudeCodeAccountRouting | null> => {
+ const bindings = await this.enabledBindings(agentId, options.provider);
+ const accounts = new Map((await this.accounts.list()).map((a) => [a.id, a]));
+ const routed = (accountId: string): ClaudeCodeRoutedAccount | undefined => {
+ const account = accounts.get(accountId);
+ if (account?.credentialMode !== QuotaCredentialMode.referenced) return;
+ if (!account.externalAccountId) return;
+ const name = account.label || account.email;
+ return { externalAccountId: account.externalAccountId, ...(name ? { name } : {}) };
+ };
+
+ const pinned = bindings.find((b) => b.role === QuotaBindingRole.pinned);
+ if (pinned) {
+ const account = routed(pinned.accountId);
+ return account ? { candidates: [account], mode: 'pinned' } : null;
+ }
+
+ const pool = bindings.filter((b) => b.role === QuotaBindingRole.pool);
+ if (pool.length === 0) return null;
+
+ const now = options.now ?? Date.now();
+ const priorityById = new Map(pool.map((b) => [b.accountId, b.priority]));
+ const loads = await this.resolveAccountLoads(
+ pool.map((b) => b.accountId),
+ now,
+ );
+ const candidates = rankAccounts(
+ loads.map((l) => ({ ...l, priority: priorityById.get(l.accountId) ?? 0 })),
+ { modelScope: options.modelScope, now },
+ ).flatMap((load) => routed(load.accountId) ?? []);
+
+ return candidates.length > 0 ? { candidates, mode: 'balanced' } : null;
+ };
+
+ /**
+ * The agent's enabled bindings. Bindings are written provider-blind; a
+ * caller that names its provider must never be routed onto another
+ * provider's account, pinned or pooled.
+ */
+ private enabledBindings = async (agentId: string, provider?: string) => {
+ const bindings = (await this.bindings.listByAgent(agentId)).filter((b) => b.enabled);
+ if (!provider) return bindings;
+
+ // One read of the caller's accounts rather than a lookup per binding.
+ const providerById = new Map((await this.accounts.list()).map((a) => [a.id, a.provider]));
+ return bindings.filter((binding) => providerById.get(binding.accountId) === provider);
+ };
+
private selectAccountId = async (
agentId: string,
options: SelectAccountOptions,
): Promise<{ accountId: string; reason: 'pinned' | 'balanced' } | null> => {
- let bindings = (await this.bindings.listByAgent(agentId)).filter((b) => b.enabled);
- // Bindings are written provider-blind; a caller that names its provider
- // must never be routed onto another provider's account, pinned or pooled.
- if (options.provider) {
- const candidates = await Promise.all(
- bindings.map((binding) => this.accounts.findById(binding.accountId)),
- );
- bindings = bindings.filter(
- (binding, index) => candidates[index]?.provider === options.provider,
- );
- }
+ const bindings = await this.enabledBindings(agentId, options.provider);
const pinned = bindings.find((b) => b.role === QuotaBindingRole.pinned);
if (pinned) return { accountId: pinned.accountId, reason: 'pinned' };
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
index d7b3e41f4ec..767b7c4cc89 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
@@ -1,9 +1,11 @@
+import { claudeCodeAgentEnvPicksLogin } from '@lobechat/heterogeneous-agents/quota';
import type { ExecAgentResult } from '@lobechat/types';
import { getWorkingDirSourcePath } from '@lobechat/types';
import debug from 'debug';
import { DeviceModel } from '@/database/models/device';
import type { ExecutionPlan } from '@/helpers/executionTarget';
+import { AgentQuotaService } from '@/server/services/agentQuota';
import { deviceGateway } from '@/server/services/deviceGateway';
import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
import { buildRemoteDeviceHeteroContext } from '@/server/services/heterogeneousAgent/remoteDeviceHeteroContext';
@@ -22,6 +24,37 @@ import { failHeteroDispatch } from './utils';
const log = debug('lobe-server:ai-agent-service');
+/**
+ * The Claude Code account the agent's Manage-accounts choice routes this run
+ * to. The device maps it to one of its own logins: without it the device
+ * always spawned on its default login, whatever account the user picked.
+ * An agent whose env picks its own login, or the quota service failing, means
+ * no routing β€” the run must not be blocked by account bookkeeping.
+ */
+const resolveClaudeAccountRouting = async (
+ deps: HeteroDispatchDeps,
+ params: {
+ agentId: string;
+ heteroType: HeteroDispatchInput['heteroType'];
+ heterogeneousProvider: HeteroDispatchInput['heterogeneousProvider'];
+ },
+) => {
+ if (params.heteroType !== 'claude-code') return;
+ if (claudeCodeAgentEnvPicksLogin(params.heterogeneousProvider?.env)) return;
+
+ try {
+ const routing = await new AgentQuotaService(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).planDeviceRouting(params.agentId, { provider: 'claude-code' });
+ return routing ?? undefined;
+ } catch (err) {
+ log('execAgent: Claude Code account routing failed: %O', err);
+ return;
+ }
+};
+
/**
* Dispatch a local CLI hetero agent to the device its execution plan routed it
* to: pick the Codex runtime, resolve and bind the working directory, build the
@@ -169,6 +202,12 @@ export const dispatchToCliDevice = async (
})
: undefined;
+ const claudeAccountRouting = await resolveClaudeAccountRouting(deps, {
+ agentId: resolvedAgentId,
+ heteroType,
+ heterogeneousProvider,
+ });
+
const authorizationError = await resolveDeviceDispatchAuthorizationFailure(
deps.db,
deps.userId,
@@ -182,6 +221,7 @@ export const dispatchToCliDevice = async (
agentId: resolvedAgentId,
// Only a live client advertising the native protocol receives these wrapper flags.
args: nativeCodex ? [...(heteroExecArgs ?? []), ...nativeCodex.args] : heteroExecArgs,
+ ...(claudeAccountRouting && { claudeAccountRouting }),
clientKinds: nativeCodex?.clientKinds,
cwd: deviceCwd,
deviceId: dispatchDeviceId,
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
index 4f7420d511b..b2896d52f62 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({
dispatchAgentRun: vi.fn(),
executeToolCall: vi.fn(),
finalizeHeteroDispatchError: vi.fn(),
+ planDeviceRouting: vi.fn(),
publishAgentRuntimeInit: vi.fn(),
readDeviceSystemInfo: vi.fn(),
recordStart: vi.fn(),
@@ -58,6 +59,12 @@ vi.mock('@/server/modules/AgentRuntime/factory', () => ({
createStreamEventManager: () => ({ publishAgentRuntimeInit: mocks.publishAgentRuntimeInit }),
}));
+vi.mock('@/server/services/agentQuota', () => ({
+ AgentQuotaService: vi.fn(function () {
+ return { planDeviceRouting: mocks.planDeviceRouting };
+ }),
+}));
+
vi.mock('@/server/services/deviceGateway', () => ({
deviceGateway: {
dispatchAgentRun: mocks.dispatchAgentRun,
@@ -182,6 +189,7 @@ beforeEach(() => {
mocks.resolveSandboxSessionConfig.mockResolvedValue(undefined);
mocks.selectCodexDeviceDispatch.mockResolvedValue({ kind: 'exec' });
mocks.dispatchAgentRun.mockResolvedValue({ success: true });
+ mocks.planDeviceRouting.mockResolvedValue(null);
mocks.executeToolCall.mockResolvedValue({ success: true });
mocks.spawnHeteroSandbox.mockResolvedValue(undefined);
mocks.publishAgentRuntimeInit.mockResolvedValue('init');
@@ -495,6 +503,56 @@ describe('dispatchHeteroAgent β€” local CLI agents', () => {
expect(result).toMatchObject({ status: 'created', success: true, token: 'user-jwt' });
});
+ it('sends the Claude Code account the agent is routed to', async () => {
+ // Without it the device always spawned on its default login, so picking an
+ // account in Manage accounts changed nothing for a device-bound agent.
+ const routing = { candidates: [{ externalAccountId: 'acc-1' }], mode: 'pinned' };
+ mocks.planDeviceRouting.mockResolvedValueOnce(routing);
+ const { deps } = createDeps();
+ const deviceCtx = {
+ boundDeviceId: 'dev-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ };
+
+ await dispatchHeteroAgent(deps, createCtx(deviceCtx), createInput('claude-code'));
+
+ expect(mocks.planDeviceRouting).toHaveBeenCalledWith('agent-1', { provider: 'claude-code' });
+ expect(mocks.dispatchAgentRun.mock.calls[0][0].claudeAccountRouting).toEqual(routing);
+ });
+
+ it('dispatches without account routing when the agent env picks the login or routing fails', async () => {
+ const { deps } = createDeps();
+
+ await dispatchHeteroAgent(
+ deps,
+ createCtx({
+ boundDeviceId: 'dev-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ }),
+ createInput('claude-code', {
+ heterogeneousProvider: { env: { ANTHROPIC_API_KEY: 'sk' }, type: 'claude-code' },
+ }),
+ );
+ expect(mocks.planDeviceRouting).not.toHaveBeenCalled();
+
+ mocks.planDeviceRouting.mockRejectedValueOnce(new Error('db down'));
+ await dispatchHeteroAgent(
+ deps,
+ createCtx({
+ boundDeviceId: 'dev-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ }),
+ createInput('claude-code'),
+ );
+
+ expect(mocks.dispatchAgentRun).toHaveBeenCalledTimes(2);
+ for (const [params] of mocks.dispatchAgentRun.mock.calls)
+ expect(params).not.toHaveProperty('claudeAccountRouting');
+ });
+
it('spawns in the source repo and names the active worktree in the context', async () => {
// The agent created this worktree last turn and may have removed it since:
// spawning in it failed every later turn with working_directory_not_found.
diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.ts
index 34731e8eae4..7ed739eefd3 100644
--- a/apps/server/src/services/deviceGateway/agents.ts
+++ b/apps/server/src/services/deviceGateway/agents.ts
@@ -10,6 +10,7 @@ import {
} from '@lobechat/device-gateway-client';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import type {
+ ClaudeCodeAccountRouting,
ClaudeCodeQuotaSnapshot,
CodexQuotaSnapshot,
KimiCodeQuotaSnapshot,
@@ -156,6 +157,8 @@ export async function dispatchAgentRun(
assistantMessageId: string;
/** Resolved `lh hetero exec` wrapper args. */
args?: string[];
+ /** Claude Code account the device must spawn on; see the request message. */
+ claudeAccountRouting?: ClaudeCodeAccountRouting;
/** Restricts the run to connections of these clients; omitted means any client. */
clientKinds?: DeviceClient[];
cwd?: string;
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index 82cd354c66b..d817492f6d6 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -6,6 +6,7 @@
"exports": {
".": "./src/index.ts",
"./agent-browser": "./src/agentBrowser.ts",
+ "./claude-code-account-routing": "./src/claudeCodeAccountRouting.ts",
"./computer-use": "./src/computerUse.ts",
"./file-preview": "./src/filePreview.ts",
"./metrics": "./src/metrics/index.ts",
diff --git a/packages/device-control/src/__tests__/claudeCodeAccountRouting.test.ts b/packages/device-control/src/__tests__/claudeCodeAccountRouting.test.ts
new file mode 100644
index 00000000000..5b205c67d28
--- /dev/null
+++ b/packages/device-control/src/__tests__/claudeCodeAccountRouting.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { resolveClaudeAccountSpawnEnv } from '../claudeCodeAccountRouting';
+
+const login = (externalAccountId: string, configDir: string | null = null) => ({
+ configDir,
+ identity: { externalAccountId },
+});
+const pinned = {
+ candidates: [{ externalAccountId: 'acc-a', name: '[email protected]' }],
+ mode: 'pinned' as const,
+};
+const balanced = {
+ candidates: [{ externalAccountId: 'acc-a' }, { externalAccountId: 'acc-b' }],
+ mode: 'balanced' as const,
+};
+
+describe('resolveClaudeAccountSpawnEnv', () => {
+ it('leaves an unrouted run on the default login without reading logins', async () => {
+ const listLogins = vi.fn();
+
+ expect(await resolveClaudeAccountSpawnEnv(undefined, { inheritedEnv: {}, listLogins })).toEqual(
+ { env: {}, kind: 'spawn' },
+ );
+ expect(listLogins).not.toHaveBeenCalled();
+ });
+
+ it('spawns a pinned profile login with its CLAUDE_CONFIG_DIR', async () => {
+ const prepareLogin = vi.fn(async () => ({
+ configDir: '/profiles/a',
+ kind: 'profile' as const,
+ }));
+
+ const result = await resolveClaudeAccountSpawnEnv(pinned, {
+ inheritedEnv: {},
+ listLogins: async () => [login('acc-b'), login('acc-a', '/profiles/a')],
+ prepareLogin,
+ });
+
+ expect(result).toEqual({ env: { CLAUDE_CONFIG_DIR: '/profiles/a' }, kind: 'spawn' });
+ expect(prepareLogin).toHaveBeenCalledWith('acc-a');
+ });
+
+ it('keeps the default login when that is the pinned account', async () => {
+ expect(
+ await resolveClaudeAccountSpawnEnv(pinned, {
+ inheritedEnv: {},
+ listLogins: async () => [login('acc-a')],
+ }),
+ ).toEqual({ env: {}, kind: 'spawn' });
+ });
+
+ it('rejects a pin this device holds no login for, naming the account', async () => {
+ const result = await resolveClaudeAccountSpawnEnv(pinned, {
+ inheritedEnv: {},
+ listLogins: async () => [login('acc-b')],
+ });
+
+ expect(result).toEqual({ kind: 'reject', reason: expect.stringContaining('[email protected]') });
+ });
+
+ it('rejects a pin when the logins cannot be read, but lets auto mode run', async () => {
+ const listLogins = async () => {
+ throw new Error('keychain locked');
+ };
+
+ expect(
+ await resolveClaudeAccountSpawnEnv(pinned, { inheritedEnv: {}, listLogins }),
+ ).toMatchObject({ kind: 'reject' });
+ expect(await resolveClaudeAccountSpawnEnv(balanced, { inheritedEnv: {}, listLogins })).toEqual({
+ env: {},
+ kind: 'spawn',
+ });
+ });
+
+ it('balances onto a candidate this device holds', async () => {
+ expect(
+ await resolveClaudeAccountSpawnEnv(balanced, {
+ inheritedEnv: {},
+ listLogins: async () => [login('acc-c'), login('acc-b', '/profiles/b')],
+ }),
+ ).toEqual({ env: { CLAUDE_CONFIG_DIR: '/profiles/b' }, kind: 'spawn' });
+ });
+
+ it('stays out of a run the device routes to an external provider', async () => {
+ const listLogins = vi.fn();
+
+ expect(
+ await resolveClaudeAccountSpawnEnv(pinned, {
+ inheritedEnv: { CLAUDE_CODE_USE_BEDROCK: '1' },
+ listLogins,
+ }),
+ ).toEqual({ env: {}, kind: 'spawn' });
+ expect(listLogins).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/device-control/src/claudeCodeAccountRouting.ts b/packages/device-control/src/claudeCodeAccountRouting.ts
new file mode 100644
index 00000000000..121e465986a
--- /dev/null
+++ b/packages/device-control/src/claudeCodeAccountRouting.ts
@@ -0,0 +1,90 @@
+import type {
+ ClaudeCodeAccountResolution,
+ ClaudeCodeAccountRouting,
+ ClaudeCodeLocalAccount,
+} from '@lobechat/heterogeneous-agents/quota';
+import {
+ claudeCodeRoutesExternally,
+ pickClaudeCodeLogin,
+} from '@lobechat/heterogeneous-agents/quota';
+import {
+ hasClaudeCodeLogin,
+ readClaudeCodeIdentity,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
+
+export interface ResolveClaudeAccountSpawnEnvDeps {
+ /** Env the spawned CLI inherits on this device (Bedrock / Vertex flags). */
+ inheritedEnv: Record<string, string | undefined>;
+ /** Every Claude Code login this device holds, default first. */
+ listLogins: () => Promise<ClaudeCodeLocalAccount[]>;
+ /**
+ * Make a profile login ready to spawn on (e.g. link its shared entries).
+ * Omitted where the device has no per-account profiles.
+ */
+ prepareLogin?: (externalAccountId: string) => Promise<ClaudeCodeAccountResolution>;
+}
+
+export type ClaudeAccountSpawnEnv =
+ { env: Record<string, string>; kind: 'spawn' } | { kind: 'reject'; reason: string };
+
+const NO_OVERRIDE: ClaudeAccountSpawnEnv = { env: {}, kind: 'spawn' };
+
+const notSignedIn = (name: string): ClaudeAccountSpawnEnv => ({
+ kind: 'reject',
+ reason: `The Claude Code account ${name} isn't signed in on this device. Sign in to it on this device, or switch to another account.`,
+});
+
+/**
+ * Turn the account the server routed a device run to into spawn env for
+ * `lh hetero exec`: `{}` keeps the device's default login, a profile login
+ * sets `CLAUDE_CONFIG_DIR`. A pinned account this device holds no login for
+ * rejects the run rather than quietly spending another account's quota.
+ */
+export const resolveClaudeAccountSpawnEnv = async (
+ routing: ClaudeCodeAccountRouting | undefined,
+ deps: ResolveClaudeAccountSpawnEnvDeps,
+): Promise<ClaudeAccountSpawnEnv> => {
+ if (!routing?.candidates.length) return NO_OVERRIDE;
+ // A Bedrock / Vertex run uses no subscription login at all.
+ if (claudeCodeRoutesExternally(undefined, deps.inheritedEnv)) return NO_OVERRIDE;
+
+ const pinnedName = routing.candidates[0].name ?? routing.candidates[0].externalAccountId;
+ let logins: ClaudeCodeLocalAccount[];
+ try {
+ logins = await deps.listLogins();
+ } catch {
+ // Auto mode may run on the default login; a pin may not run on a guess.
+ return routing.mode === 'pinned' ? notSignedIn(pinnedName) : NO_OVERRIDE;
+ }
+
+ const picked = pickClaudeCodeLogin(routing, logins);
+ if (picked.kind === 'pinned-missing') return notSignedIn(pinnedName);
+ if (picked.kind === 'default' || !picked.login.configDir) return NO_OVERRIDE;
+
+ if (!deps.prepareLogin)
+ return { env: { CLAUDE_CONFIG_DIR: picked.login.configDir }, kind: 'spawn' };
+
+ const resolution = await deps
+ .prepareLogin(picked.account.externalAccountId)
+ .catch((): ClaudeCodeAccountResolution => ({ kind: 'missing' }));
+ if (resolution.kind === 'profile')
+ return { env: { CLAUDE_CONFIG_DIR: resolution.configDir }, kind: 'spawn' };
+ if (resolution.kind === 'default') return NO_OVERRIDE;
+ // Signed out between the listing and the spawn.
+ return routing.mode === 'pinned'
+ ? notSignedIn(picked.account.name ?? picked.account.externalAccountId)
+ : NO_OVERRIDE;
+};
+
+/**
+ * The only login a plain CLI device holds: whatever `claude` uses with the
+ * env it inherits (`CLAUDE_CONFIG_DIR`, else `~/.claude`).
+ */
+export const listDefaultClaudeLogin = async (
+ env: Record<string, string | undefined>,
+): Promise<ClaudeCodeLocalAccount[]> => {
+ const identity = await readClaudeCodeIdentity({ env });
+ if (!identity?.externalAccountId) return [];
+ if (!(await hasClaudeCodeLogin({ env }))) return [];
+ return [{ configDir: null, identity }];
+};
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 60bfdb4e6e1..41e44fbd6ec 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -7,6 +7,7 @@ import {
type DeviceUnavailableErrorData,
} from './deviceTransportError';
import type {
+ AgentRunRequestMessage,
DeviceSystemInfo,
GatewayDevice,
GatewayMcpParams,
@@ -317,6 +318,7 @@ export class GatewayHttpClient {
assistantMessageId: string;
/** Resolved `lh hetero exec` wrapper args. */
args?: string[];
+ claudeAccountRouting?: AgentRunRequestMessage['claudeAccountRouting'];
/** 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.ts
index 8dd86e3e661..ca533788445 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -259,6 +259,17 @@ export interface AgentRunRequestMessage {
args?: string[];
/** Seed assistant message that receives terminal state from the CLI run. */
assistantMessageId?: string;
+ /**
+ * Claude Code subscription account the agent is routed to (its pin, or its
+ * auto-balanced pool best-first). The device maps it to a local login and
+ * spawns with that login's `CLAUDE_CONFIG_DIR`; a pinned account it holds no
+ * login for rejects the run. Optional β€” omitted for unbound agents, other
+ * agent types and older servers; an older device ignores it.
+ */
+ claudeAccountRouting?: {
+ candidates: Array<{ externalAccountId: string; name?: string }>;
+ mode: 'balanced' | 'pinned';
+ };
cwd?: string;
/**
* Image attachments from the user message, as URLs the device can fetch
diff --git a/packages/heterogeneous-agents/src/quota/claudeCodeRouting.test.ts b/packages/heterogeneous-agents/src/quota/claudeCodeRouting.test.ts
index 27109a4469f..7e9724bb912 100644
--- a/packages/heterogeneous-agents/src/quota/claudeCodeRouting.test.ts
+++ b/packages/heterogeneous-agents/src/quota/claudeCodeRouting.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { claudeCodeRoutesExternally } from './claudeCodeRouting';
+import {
+ claudeCodeAgentEnvPicksLogin,
+ claudeCodeRoutesExternally,
+ pickClaudeCodeLogin,
+} from './claudeCodeRouting';
describe('claudeCodeRoutesExternally', () => {
it.each([
@@ -18,3 +22,49 @@ describe('claudeCodeRoutesExternally', () => {
expect(claudeCodeRoutesExternally(agentEnv, inherited)).toBe(expected);
});
});
+
+describe('pickClaudeCodeLogin', () => {
+ const login = (externalAccountId: string, configDir: string | null = null) => ({
+ configDir,
+ identity: { externalAccountId },
+ });
+ const a = { externalAccountId: 'acc-a', name: '[email protected]' };
+ const b = { externalAccountId: 'acc-b', name: '[email protected]' };
+
+ it('runs a pin on its login, and never on another one', () => {
+ const local = [login('acc-b'), login('acc-a', '/profiles/a')];
+
+ expect(pickClaudeCodeLogin({ candidates: [a], mode: 'pinned' }, local)).toEqual({
+ account: a,
+ kind: 'login',
+ login: local[1],
+ });
+ expect(pickClaudeCodeLogin({ candidates: [a], mode: 'pinned' }, [login('acc-b')])).toEqual({
+ account: a,
+ kind: 'pinned-missing',
+ });
+ });
+
+ it('balances onto the best candidate this device holds, else keeps the default login', () => {
+ const routing = { candidates: [a, b], mode: 'balanced' } as const;
+
+ expect(pickClaudeCodeLogin(routing, [login('acc-b')])).toMatchObject({
+ account: b,
+ kind: 'login',
+ });
+ expect(pickClaudeCodeLogin(routing, [login('acc-b'), login('acc-a', '/p/a')])).toMatchObject({
+ account: a,
+ });
+ expect(pickClaudeCodeLogin(routing, [login('acc-c')])).toEqual({ kind: 'default' });
+ });
+});
+
+describe('claudeCodeAgentEnvPicksLogin', () => {
+ it('treats a login, credential or external-provider env as the agent choosing', () => {
+ expect(claudeCodeAgentEnvPicksLogin(undefined)).toBe(false);
+ expect(claudeCodeAgentEnvPicksLogin({ CLAUDE_CONFIG_DIR: ' ' })).toBe(false);
+ expect(claudeCodeAgentEnvPicksLogin({ CLAUDE_CONFIG_DIR: '/x' })).toBe(true);
+ expect(claudeCodeAgentEnvPicksLogin({ ANTHROPIC_API_KEY: 'sk' })).toBe(true);
+ expect(claudeCodeAgentEnvPicksLogin({ CLAUDE_CODE_USE_BEDROCK: '1' })).toBe(true);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/quota/claudeCodeRouting.ts b/packages/heterogeneous-agents/src/quota/claudeCodeRouting.ts
index cc8616d5093..4bf2d1b598b 100644
--- a/packages/heterogeneous-agents/src/quota/claudeCodeRouting.ts
+++ b/packages/heterogeneous-agents/src/quota/claudeCodeRouting.ts
@@ -30,3 +30,81 @@ export const claudeCodeRoutesExternally = (
CLAUDE_CODE_EXTERNAL_ROUTING_ENV_KEYS.some((key) =>
isClaudeCodeRoutingFlagEnabled(agentEnv && key in agentEnv ? agentEnv[key] : inheritedEnv[key]),
);
+
+/**
+ * Agent env keys that already choose which login (or credential) the CLI
+ * uses. With any of these set, subscription account routing could only be
+ * overridden β€” or, worse, block the run over a pin the agent does not use.
+ */
+export const CLAUDE_CODE_AGENT_LOGIN_ENV_KEYS = [
+ 'CLAUDE_CONFIG_DIR',
+ 'ANTHROPIC_API_KEY',
+ 'ANTHROPIC_AUTH_TOKEN',
+ 'ANTHROPIC_BASE_URL',
+] as const;
+
+/** Whether the agent's own env decides the login, so account routing must stay out. */
+export const claudeCodeAgentEnvPicksLogin = (
+ agentEnv: Record<string, string | undefined> | undefined,
+): boolean =>
+ CLAUDE_CODE_AGENT_LOGIN_ENV_KEYS.some((key) => agentEnv?.[key]?.trim()) ||
+ claudeCodeRoutesExternally(agentEnv);
+
+/** One account the server routed a device run to. */
+export interface ClaudeCodeRoutedAccount {
+ externalAccountId: string;
+ /** Display name for errors: the account label, else its email. */
+ name?: string;
+}
+
+/**
+ * The account choice the server sends with a device run. The server knows the
+ * agent's bindings and every account's quota; only the device knows which of
+ * those accounts it holds a login for, so it makes the final pick.
+ *
+ * - `pinned`: the run must use `candidates[0]`, or not run at all.
+ * - `balanced`: the run uses the first candidate (best headroom first) the
+ * device holds a login for.
+ */
+export interface ClaudeCodeAccountRouting {
+ candidates: ClaudeCodeRoutedAccount[];
+ mode: 'balanced' | 'pinned';
+}
+
+interface RoutableLogin {
+ identity: { externalAccountId?: string | null };
+}
+
+export type ClaudeCodeRoutedLogin<T extends RoutableLogin = RoutableLogin> =
+ /** Spawn with this login. */
+ | { account: ClaudeCodeRoutedAccount; kind: 'login'; login: T }
+ /** Leave the spawn on the device's default login, as before routing existed. */
+ | { kind: 'default' }
+ /** The pinned account has no login on this device: the run must not start. */
+ | { account: ClaudeCodeRoutedAccount; kind: 'pinned-missing' };
+
+/**
+ * Map the server's account choice onto the logins one device holds. A pin
+ * never falls back to another login. Auto mode with none of its accounts here
+ * keeps the default login: the rotation may be built from other machines'
+ * logins, and that must not stop a device that ran fine before routing.
+ */
+export const pickClaudeCodeLogin = <T extends RoutableLogin>(
+ routing: ClaudeCodeAccountRouting,
+ localAccounts: T[],
+): ClaudeCodeRoutedLogin<T> => {
+ const candidates =
+ routing.mode === 'pinned' ? routing.candidates.slice(0, 1) : routing.candidates;
+
+ for (const account of candidates) {
+ const login = localAccounts.find(
+ (local) => local.identity.externalAccountId === account.externalAccountId,
+ );
+ if (login) return { account, kind: 'login', login };
+ }
+
+ if (routing.mode === 'pinned' && routing.candidates[0])
+ return { account: routing.candidates[0], kind: 'pinned-missing' };
+
+ return { kind: 'default' };
+};
diff --git a/packages/heterogeneous-agents/src/quota/loadBalancer.ts b/packages/heterogeneous-agents/src/quota/loadBalancer.ts
index ea4fa85bb4a..dd8319c7a9d 100644
--- a/packages/heterogeneous-agents/src/quota/loadBalancer.ts
+++ b/packages/heterogeneous-agents/src/quota/loadBalancer.ts
@@ -52,6 +52,31 @@ const scopedHeadroom = (a: AccountLoad, modelScope?: string): number => {
return scoped == null ? 100 : 100 - scoped;
};
+/**
+ * Every eligible account, best first. A caller that may not be able to run the
+ * top pick (a device holds only some of the logins) walks this order instead
+ * of asking again.
+ */
+export const rankAccounts = (
+ candidates: AccountLoad[],
+ opts: SelectAccountOptions,
+): AccountLoad[] =>
+ candidates
+ .filter((a) => isEligible(a, opts))
+ .sort((a, b) => {
+ // 1) weekly headroom (the bottleneck) β€” more is better
+ const weekly = 100 - (a.weeklyUtil ?? 0) - (100 - (b.weeklyUtil ?? 0));
+ if (weekly !== 0) return -weekly;
+ // 2) scoped headroom for the requested model
+ const scoped = scopedHeadroom(a, opts.modelScope) - scopedHeadroom(b, opts.modelScope);
+ if (scoped !== 0) return -scoped;
+ // 3) session headroom
+ const session = 100 - (a.sessionUtil ?? 0) - (100 - (b.sessionUtil ?? 0));
+ if (session !== 0) return -session;
+ // 4) explicit priority (lower first)
+ return a.priority - b.priority;
+ });
+
/**
* Pick the account an agent should run on. Returns null when every candidate is
* exhausted or cooling down (caller then queues / rolls the task over).
@@ -59,21 +84,4 @@ const scopedHeadroom = (a: AccountLoad, modelScope?: string): number => {
export const selectAccount = (
candidates: AccountLoad[],
opts: SelectAccountOptions,
-): AccountLoad | null => {
- const eligible = candidates.filter((a) => isEligible(a, opts));
- if (eligible.length === 0) return null;
-
- return eligible.sort((a, b) => {
- // 1) weekly headroom (the bottleneck) β€” more is better
- const weekly = 100 - (a.weeklyUtil ?? 0) - (100 - (b.weeklyUtil ?? 0));
- if (weekly !== 0) return -weekly;
- // 2) scoped headroom for the requested model
- const scoped = scopedHeadroom(a, opts.modelScope) - scopedHeadroom(b, opts.modelScope);
- if (scoped !== 0) return -scoped;
- // 3) session headroom
- const session = 100 - (a.sessionUtil ?? 0) - (100 - (b.sessionUtil ?? 0));
- if (session !== 0) return -session;
- // 4) explicit priority (lower first)
- return a.priority - b.priority;
- })[0];
-};
+): AccountLoad | null => rankAccounts(candidates, opts)[0] ?? null;
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts
index 869398cefca..1180e765703 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts
@@ -1,4 +1,7 @@
-import { claudeCodeRoutesExternally } from '@lobechat/heterogeneous-agents/quota';
+import {
+ claudeCodeAgentEnvPicksLogin,
+ claudeCodeRoutesExternally,
+} from '@lobechat/heterogeneous-agents/quota';
import { t } from 'i18next';
import { agentQuotaService } from '@/services/agentQuota';
@@ -38,23 +41,6 @@ const resolveLocalLogin = async (selection: AccountSelection) => {
}
};
-/**
- * Agent env keys that already choose which login (or credential) the CLI
- * uses. The executor spreads the agent's env last, so with any of these set
- * account routing could only be overridden β€” or, worse, block the run over a
- * pin the agent does not even use.
- */
-const AGENT_LOGIN_ENV_KEYS = [
- 'CLAUDE_CONFIG_DIR',
- 'ANTHROPIC_API_KEY',
- 'ANTHROPIC_AUTH_TOKEN',
- 'ANTHROPIC_BASE_URL',
-] as const;
-
-/** The agent's own env decides the login, so subscription routing must stay out. */
-const agentEnvPicksLogin = (env?: Record<string, string>) =>
- AGENT_LOGIN_ENV_KEYS.some((key) => env?.[key]?.trim()) || claudeCodeRoutesExternally(env);
-
/**
* Bedrock / Mantle / Vertex flags the desktop process exports reach the CLI
* too, unless the agent env overrides them β€” a run on an external provider
@@ -83,7 +69,7 @@ const inheritedEnvRoutesExternally = async (agentEnv?: Record<string, string>) =
* No bindings, or the quota service unreachable, β†’ `{}` and the spawn behaves
* as before; a desktop that fails to look up its logins fails the run. An env
* that picks its own login or an external provider β€” the agent's
- * (`agentEnvPicksLogin`) or one inherited from the desktop β€” wins over
+ * (`claudeCodeAgentEnvPicksLogin`) or one inherited from the desktop β€” wins over
* routing; the result is also spread BEFORE `heterogeneousProvider.env` for
* the same reason.
*/
@@ -94,7 +80,7 @@ export const resolveQuotaAccountSpawnPlan = async (
): Promise<QuotaAccountSpawnPlan> => {
// Codex accounts exist in the DB but have no runnable credential mapping yet.
if (adapterType !== 'claude-code' || !agentId) return NO_ROUTING;
- if (agentEnvPicksLogin(agentEnv)) return NO_ROUTING;
+ if (claudeCodeAgentEnvPicksLogin(agentEnv)) return NO_ROUTING;
const select = (runnableExternalAccountIds?: string[]) =>
agentQuotaService