🤯 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
♻️ refactor(hetero-agent): centralize local CLI descriptors as single source of truth (#17979)
AmAzing-17384f442010
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 0f1d86fdb14..d45165bea1b 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -3,11 +3,13 @@ import { tmpdir } from 'node:os';import path from 'node:path';import { PassThrough } from 'node:stream';+import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import { HETEROGENEOUS_AGENT_CONFIGS } from '@lobechat/heterogeneous-agents';import type * as HeteroSpawn from '@lobechat/heterogeneous-agents/spawn';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { registerHeteroCommand } from './hetero';+import { registerHeteroCommand, SUPPORTED_AGENT_TYPES } from './hetero';const { mockResolveHeteroSpawnCommand, mockSpawnAgent } = vi.hoisted(() => ({mockResolveHeteroSpawnCommand: vi.fn(),@@ -102,10 +104,7 @@ describe('hetero exec command', () => {stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);mockResolveHeteroSpawnCommand.mockReset();mockResolveHeteroSpawnCommand.mockImplementation(- async (- agentType: 'amp' | 'claude-code' | 'codex' | 'opencode' | 'pi' | 'qoder',- command?: string,- ) => ({+ async (agentType: LocalHeterogeneousAgentType, command?: string) => ({command:command ??(agentType === 'amp'@@ -164,6 +163,12 @@ describe('hetero exec command', () => {}};+ it('supports exactly the local agent descriptor types', () => {+ expect([...SUPPORTED_AGENT_TYPES].toSorted()).toEqual(+ HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type).toSorted(),+ );+ });+it('rejects unsupported agent types via process.exit(2)', async () => {await runCmd(['hetero', 'exec', '--type', 'kimi-cli', '--prompt', 'hi']);expect(exitSpy).toHaveBeenCalledWith(2);diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex 9cb203eb377..0810f39294d 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -5,6 +5,11 @@ import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';+import {+ HETEROGENEOUS_AGENT_CONFIGS,+ isLocalHeterogeneousType,+ LOCAL_HETEROGENEOUS_AGENT_TYPES,+} from '@lobechat/heterogeneous-agents';import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';import { LobeBuiltinMcpServer } from '@lobechat/heterogeneous-agents/builtinMcp';import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';@@ -28,7 +33,8 @@ import { CoalescingBatchIngester } from '../utils/CoalescingBatchIngester';import { log } from '../utils/logger';import { TrpcIngestSink } from '../utils/TrpcIngestSink';-const SUPPORTED_AGENT_TYPES = new Set(['amp', 'claude-code', 'codex', 'opencode', 'pi', 'qoder']);+export const SUPPORTED_AGENT_TYPES = new Set<string>(LOCAL_HETEROGENEOUS_AGENT_TYPES);+const SUPPORTED_AGENT_TITLES = HETEROGENEOUS_AGENT_CONFIGS.map(({ title }) => title).join(' / ');const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';@@ -333,7 +339,7 @@ class RawStreamDump {}const exec = async (options: ExecOptions): Promise<void> => {- if (!SUPPORTED_AGENT_TYPES.has(options.type)) {+ if (!isLocalHeterogeneousType(options.type)) {log.error(`Unsupported --type "${options.type}". Supported: ${[...SUPPORTED_AGENT_TYPES].join(', ')}`,);@@ -385,7 +391,7 @@ const exec = async (options: ExecOptions): Promise<void> => {// Build the ingest sink — no-op for standalone mode, real tRPC sink for// server-ingest mode. The tRPC client reads LOBEHUB_JWT (operation-scoped// JWT injected by the server) for authentication.- const agentType = options.type as 'amp' | 'claude-code' | 'codex' | 'opencode' | 'pi' | 'qoder';+ const agentType = options.type;let sink: TrpcIngestSink | undefined;let serverIngester: CoalescingBatchIngester | undefined;// Uploader for tool_result images (CC `Read` on an image file). Reuses the@@ -525,7 +531,12 @@ const exec = async (options: ExecOptions): Promise<void> => {type: string,errnoCode?: string,): { body?: Record<string, unknown>; message: string; type: string } => {- const classified = classifyHeteroProcessFailure({ agentType, detail: message, errnoCode });+ const classified = classifyHeteroProcessFailure({+ agentType,+ command: options.command,+ detail: message,+ errnoCode,+ });if (!classified) return { message, type };return { body: { ...classified }, message: classified.message, type: 'AgentRuntimeError' };};@@ -889,7 +900,7 @@ export function registerHeteroCommand(program: Command) {const hetero = program.command('hetero').description(- 'Run heterogeneous agent CLIs (Amp / Claude Code / Codex / OpenCode / Pi / Qoder) and stream their output',+ `Run heterogeneous agent CLIs (${SUPPORTED_AGENT_TITLES}) and stream their output`,);heterodiff --git a/apps/cli/src/utils/TrpcIngestSink.ts b/apps/cli/src/utils/TrpcIngestSink.tsindex b75e89712ab..f035ebae431 100644--- a/apps/cli/src/utils/TrpcIngestSink.ts+++ b/apps/cli/src/utils/TrpcIngestSink.ts@@ -1,3 +1,4 @@+import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';import type { TrpcClient } from '../api/client';@@ -13,7 +14,7 @@ import type { IngestSink } from './BatchIngester';export class TrpcIngestSink implements IngestSink {constructor(private readonly client: TrpcClient,- private readonly agentType: 'amp' | 'claude-code' | 'codex' | 'opencode' | 'pi' | 'qoder',+ private readonly agentType: LocalHeterogeneousAgentType,private readonly operationId: string,private readonly topicId: string,private readonly assistantMessageId?: string,diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 7a0340920c0..4f2ecdd402e 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -15,22 +15,14 @@ import type {HeterogeneousAgentSessionError,HeterogeneousCliAgentType,} from '@lobechat/electron-client-ipc';+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc/types/heterogeneous-agent';import {- AMP_CLI_INSTALL_COMMANDS,- AMP_CLI_INSTALL_DOCS_URL,- CLAUDE_CODE_CLI_INSTALL_COMMANDS,- CLAUDE_CODE_CLI_INSTALL_DOCS_URL,- CODEX_CLI_INSTALL_COMMANDS,- CODEX_CLI_INSTALL_DOCS_URL,- HeterogeneousAgentSessionErrorCode,- OPENCODE_CLI_INSTALL_COMMANDS,- OPENCODE_CLI_INSTALL_DOCS_URL,- PI_CLI_INSTALL_COMMANDS,- PI_CLI_INSTALL_DOCS_URL,- QODER_CLI_AUTH_DOCS_URL,- QODER_CLI_INSTALL_COMMANDS,- QODER_CLI_INSTALL_DOCS_URL,-} from '@lobechat/electron-client-ipc/types/heterogeneous-agent';+ buildHeterogeneousAgentAuthRequiredError,+ buildHeterogeneousAgentCliNotFoundError,+ getHeterogeneousAgentConfigOrThrow,+ isHeterogeneousAgentAuthRequired,+ resolveHeterogeneousAgentCommand,+} from '@lobechat/heterogeneous-agents';import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';import type {LobeBuiltinMcpServer,@@ -128,18 +120,6 @@ const CODEX_RESUME_THREAD_NOT_FOUND_PATTERNS = [/conversation .*not found/i,/resume.*not found/i,] as const;-const CLI_AUTH_REQUIRED_PATTERNS = [- /failed to authenticate/i,- /invalid authentication credentials/i,- /authentication[_ ]error/i,- /not authenticated/i,- /\bunauthorized\b/i,- /\b401\b/,- /no api key found/i,- /no models available/i,-] as const;-const AMP_AUTH_REQUIRED_PATTERNS = [/please (?:log|sign) in/i, /amp_api_key/i] as const;-const QODER_AUTH_REQUIRED_PATTERNS = [/not logged in/i, /please run \/login/i] as const;const CODEX_RESUME_CWD_MISMATCH_PATTERNS = [/working directory/i,/\bcwd\b/i,@@ -414,210 +394,25 @@ export default class HeterogeneousAgentCtr {);private resolveSessionCommand(session: AgentSession): string {- const resolvedCommand = session.command.trim();- if (resolvedCommand) return resolvedCommand;-- switch (session.agentType) {- case 'amp': {- return 'amp';- }- case 'codex': {- return 'codex';- }- case 'opencode': {- return 'opencode';- }- case 'pi': {- return 'pi';- }- case 'qoder': {- return 'qodercli';- }- default: {- return 'claude';- }- }+ return resolveHeterogeneousAgentCommand(session.agentType, session.command);}- private buildAmpCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {- const command = this.resolveSessionCommand(session);-- return {- agentType: 'amp',- code: HeterogeneousAgentSessionErrorCode.CliNotFound,- command,- docsUrl: AMP_CLI_INSTALL_DOCS_URL,- installCommands: AMP_CLI_INSTALL_COMMANDS,- message: `Amp CLI was not found. Install it and make sure \`${command}\` can be executed.`,- };- }-- private buildCodexCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {- const command = this.resolveSessionCommand(session);-- return {- agentType: 'codex',- code: HeterogeneousAgentSessionErrorCode.CliNotFound,- command,- docsUrl: CODEX_CLI_INSTALL_DOCS_URL,- installCommands: CODEX_CLI_INSTALL_COMMANDS,- message: `Codex CLI was not found. Install it and make sure \`${command}\` can be executed.`,- };- }-- private buildClaudeCodeCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {- const command = this.resolveSessionCommand(session);-- return {- agentType: 'claude-code',- code: HeterogeneousAgentSessionErrorCode.CliNotFound,- command,- docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,- installCommands: CLAUDE_CODE_CLI_INSTALL_COMMANDS,- message: `Claude Code CLI was not found. Install it and make sure \`${command}\` can be executed.`,- };- }-- private buildOpenCodeCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {- const command = this.resolveSessionCommand(session);-- return {- agentType: 'opencode',- code: HeterogeneousAgentSessionErrorCode.CliNotFound,- command,- docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,- installCommands: OPENCODE_CLI_INSTALL_COMMANDS,- message: `OpenCode CLI was not found. Install it and make sure \`${command}\` can be executed.`,- };- }-- private buildPiCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {- const command = this.resolveSessionCommand(session);-- return {- agentType: 'pi',- code: HeterogeneousAgentSessionErrorCode.CliNotFound,- command,- docsUrl: PI_CLI_INSTALL_DOCS_URL,- installCommands: PI_CLI_INSTALL_COMMANDS,- message: `Pi CLI was not found. Install it and make sure \`${command}\` can be executed.`,- };- }-- private buildQoderCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {- const command = this.resolveSessionCommand(session);-- return {- agentType: 'qoder',- code: HeterogeneousAgentSessionErrorCode.CliNotFound,- command,- docsUrl: QODER_CLI_INSTALL_DOCS_URL,- installCommands: QODER_CLI_INSTALL_COMMANDS,- message: `Qoder CLI was not found. Install it and make sure \`${command}\` can be executed.`,- };- }-- private buildCliMissingError(session: AgentSession): HeterogeneousAgentSessionError | undefined {- switch (session.agentType) {- case 'amp': {- return this.buildAmpCliMissingError(session);- }- case 'claude-code': {- return this.buildClaudeCodeCliMissingError(session);- }- case 'codex': {- return this.buildCodexCliMissingError(session);- }- case 'opencode': {- return this.buildOpenCodeCliMissingError(session);- }- case 'pi': {- return this.buildPiCliMissingError(session);- }- case 'qoder': {- return this.buildQoderCliMissingError(session);- }- default: {- return;- }- }+ private buildCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {+ return buildHeterogeneousAgentCliNotFoundError({+ agentType: session.agentType,+ command: session.command,+ });}private buildCliAuthRequiredError(session: AgentSession,stderr: string,- ): HeterogeneousAgentSessionError | undefined {- const command = this.resolveSessionCommand(session);-- switch (session.agentType) {- case 'amp': {- return {- agentType: 'amp',- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- command,- docsUrl: AMP_CLI_INSTALL_DOCS_URL,- message:- 'Amp could not authenticate. Run `amp login` or configure AMP_API_KEY, then retry.',- stderr,- };- }- case 'claude-code': {- return {- agentType: 'claude-code',- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- command,- docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,- message:- 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',- stderr,- };- }- case 'codex': {- return {- agentType: 'codex',- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- command,- docsUrl: CODEX_CLI_INSTALL_DOCS_URL,- message:- 'Codex could not authenticate. Sign in again or refresh its credentials, then retry.',- stderr,- };- }- case 'opencode': {- return {- agentType: 'opencode',- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- command,- docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,- message:- 'OpenCode could not authenticate. Sign in again or refresh its credentials, then retry.',- stderr,- };- }- case 'pi': {- return {- agentType: 'pi',- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- command,- docsUrl: PI_CLI_INSTALL_DOCS_URL,- message: 'Pi could not authenticate. Run `pi`, use `/login`, then retry.',- stderr,- };- }- case 'qoder': {- return {- agentType: 'qoder',- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- command,- docsUrl: QODER_CLI_AUTH_DOCS_URL,- message: 'Qoder could not authenticate. Run `qodercli login`, then retry.',- stderr,- };- }- default: {- return;- }- }+ ): HeterogeneousAgentSessionError {+ return buildHeterogeneousAgentAuthRequiredError({+ agentType: session.agentType,+ command: session.command,+ stderr,+ });}private getErrorMessage(error: unknown): string | undefined {@@ -690,13 +485,7 @@ export default class HeterogeneousAgentCtr {const message = this.getErrorMessage(error);if (!message) return;- const patterns =- session.agentType === 'amp'- ? [...CLI_AUTH_REQUIRED_PATTERNS, ...AMP_AUTH_REQUIRED_PATTERNS]- : session.agentType === 'qoder'- ? [...CLI_AUTH_REQUIRED_PATTERNS, ...QODER_AUTH_REQUIRED_PATTERNS]- : CLI_AUTH_REQUIRED_PATTERNS;- if (!patterns.some((pattern) => pattern.test(message))) return;+ if (!isHeterogeneousAgentAuthRequired(session.agentType, message)) return;return this.buildCliAuthRequiredError(session, message);}@@ -762,21 +551,7 @@ export default class HeterogeneousAgentCtr {private async getSpawnPreflightError(session: AgentSession,): Promise<HeterogeneousAgentSessionError | undefined> {- const defaultCommand =- session.agentType === 'amp'- ? 'amp'- : session.agentType === 'claude-code'- ? 'claude'- : session.agentType === 'codex'- ? 'codex'- : session.agentType === 'opencode'- ? 'opencode'- : session.agentType === 'pi'- ? 'pi'- : session.agentType === 'qoder'- ? 'qodercli'- : undefined;- if (!defaultCommand) return;+ const defaultCommand = getHeterogeneousAgentConfigOrThrow(session.agentType).defaultCommand;const command = this.resolveSessionCommand(session);const status =diff --git a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.tsindex fbbb833773c..c009db66fc5 100644--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts@@ -1,3 +1,4 @@+import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import {detectHeterogeneousCliCommand,detectValidatedCommand,@@ -166,15 +167,22 @@ export const aiderBinary: BinarySpec = defineCommandBinary('aider', {/*** All CLI agent binaries*/+export const heterogeneousCliAgentBinaries = {+ 'amp': ampBinary,+ 'claude-code': claudeCodeBinary,+ 'codex': codexBinary,+ 'opencode': opencodeBinary,+ 'pi': piBinary,+ 'qoder': qoderBinary,+} satisfies Record<LocalHeterogeneousAgentType, BinarySpec>;+export const cliAgentBinaries: BinarySpec[] = [- claudeCodeBinary,- codexBinary,- ampBinary,- opencodeBinary,- piBinary,- qoderBinary,+ ...Object.values(heterogeneousCliAgentBinaries),geminiCliBinary,qwenCodeBinary,kimiCliBinary,aiderBinary,];++export const listHeterogeneousCliBinaryTypes = (): LocalHeterogeneousAgentType[] =>+ Object.keys(heterogeneousCliAgentBinaries) as LocalHeterogeneousAgentType[];diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts b/apps/desktop/src/main/modules/heterogeneousAgent/index.tsindex 5c3712791bf..7270d7b4bf9 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts@@ -1,3 +1,5 @@+import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import { ampDriver } from './drivers/amp';import { claudeCodeDriver } from './drivers/claudeCode';import { codexDriver } from './drivers/codex';@@ -6,17 +8,17 @@ import { piDriver } from './drivers/pi';import { qoderDriver } from './drivers/qoder';import type { HeterogeneousAgentDriver } from './types';-const heterogeneousAgentDrivers: Record<string, HeterogeneousAgentDriver> = {+const heterogeneousAgentDrivers = {'amp': ampDriver,'claude-code': claudeCodeDriver,'codex': codexDriver,'opencode': opencodeDriver,'pi': piDriver,'qoder': qoderDriver,-};+} satisfies Record<LocalHeterogeneousAgentType, HeterogeneousAgentDriver>;export const getHeterogeneousAgentDriver = (agentType: string): HeterogeneousAgentDriver => {- const driver = heterogeneousAgentDrivers[agentType];+ const driver = heterogeneousAgentDrivers[agentType as LocalHeterogeneousAgentType];if (!driver) {throw new Error(`Unknown heterogeneous agent type: ${agentType}`);@@ -24,3 +26,6 @@ export const getHeterogeneousAgentDriver = (agentType: string): HeterogeneousAgereturn driver;};++export const listHeterogeneousAgentDriverTypes = (): LocalHeterogeneousAgentType[] =>+ Object.keys(heterogeneousAgentDrivers) as LocalHeterogeneousAgentType[];diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/registryConsistency.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/registryConsistency.test.tsnew file mode 100644index 00000000000..f62ba6f7930--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/registryConsistency.test.ts@@ -0,0 +1,25 @@+import { HETEROGENEOUS_AGENT_CONFIGS, listLocalAgentTypes } from '@lobechat/heterogeneous-agents';+import { describe, expect, it, vi } from 'vitest';++import { listHeterogeneousCliBinaryTypes } from '../binaries/cliAgentBinaries';+import { listHeterogeneousAgentDriverTypes } from '.';++vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ verbose: vi.fn(),+ warn: vi.fn(),+ }),+}));++describe('heterogeneous agent registry consistency', () => {+ it('keeps every executable registry aligned with the descriptor catalog', () => {+ const descriptorTypes = HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type).toSorted();++ expect(listLocalAgentTypes().toSorted()).toEqual(descriptorTypes);+ expect(listHeterogeneousAgentDriverTypes().toSorted()).toEqual(descriptorTypes);+ expect(listHeterogeneousCliBinaryTypes().toSorted()).toEqual(descriptorTypes);+ });+});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 460af32ef54..102688fb4a3 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -40,6 +40,7 @@ import {type ToolSource,} from '@lobechat/context-engine';import type { LobeChatDatabase } from '@lobechat/database';+import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';import { buildTaskManagerDefaultsPrompt, resourcesTreePrompt } from '@lobechat/prompts';import type {@@ -1918,8 +1919,7 @@ export class AiAgentService {// with the inbox write guard via `isHeterogeneousAgentModelId`).const heteroProviderType = agentConfig.agencyConfig?.heterogeneousProvider?.type;const isHeteroAgent = !!heteroProviderType || isHeterogeneousAgentModelId(model);- const heteroType = (heteroProviderType ?? model) as- 'amp' | 'claude-code' | 'codex' | 'hermes' | 'openclaw' | 'opencode' | 'pi' | 'qoder';+ const heteroType = (heteroProviderType ?? model) as HeterogeneousAgentType;// ── Shared turn setup (runs for BOTH hetero and normal agents) ──────────// Everything up to and including persisting the turn is identical for bothdiff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 8836a60e46a..68dd42efb4f 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -1,6 +1,7 @@import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { type ISnapshotStore, parseOperationId } from '@lobechat/agent-tracing';import type { LobeChatDatabase } from '@lobechat/database';+import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -22,7 +23,7 @@ import { HeteroTraceRecorder } from './HeteroTraceRecorder';const log = debug('lobe-server:hetero-agent-service');-export type HeterogeneousAgentType = 'amp' | 'claude-code' | 'codex' | 'opencode' | 'pi' | 'qoder';+export type HeterogeneousAgentType = LocalHeterogeneousAgentType;export type HeterogeneousFinishResult = 'success' | 'error' | 'cancelled';diff --git a/packages/electron-client-ipc/src/types/binary.ts b/packages/electron-client-ipc/src/types/binary.tsindex 19846861b03..11a533d9173 100644--- a/packages/electron-client-ipc/src/types/binary.ts+++ b/packages/electron-client-ipc/src/types/binary.ts@@ -1,3 +1,8 @@+import type {+ HeterogeneousAgentType,+ LocalHeterogeneousAgentType,+} from '@lobechat/heterogeneous-agents';+/*** Status of a registered binary*/@@ -23,10 +28,9 @@ export interface BinaryInfo {priority?: number;}-export type HeterogeneousCliAgentType =- 'amp' | 'claude-code' | 'codex' | 'opencode' | 'pi' | 'qoder';+export type HeterogeneousCliAgentType = LocalHeterogeneousAgentType;-export type DetectableHeterogeneousAgentType = HeterogeneousCliAgentType | 'hermes' | 'openclaw';+export type DetectableHeterogeneousAgentType = HeterogeneousAgentType;export interface DetectHeterogeneousAgentCommandParams {agentType: DetectableHeterogeneousAgentType;diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.tsindex 673d64b8db4..d0cb0199f54 100644--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts@@ -2,47 +2,21 @@ import type { HeteroQuotaWindow } from '@lobechat/heterogeneous-agents/quota';import type { HeterogeneousCliAgentType } from './binary';-export const AMP_CLI_INSTALL_DOCS_URL = 'https://ampcode.com/manual';--export const AMP_CLI_INSTALL_COMMANDS = [- 'curl -fsSL https://ampcode.com/install.sh | bash',- 'brew install ampcode/tap/ampcode',-] as const;--export const CLAUDE_CODE_CLI_INSTALL_DOCS_URL =- 'https://docs.anthropic.com/en/docs/claude-code/setup';--export const CLAUDE_CODE_CLI_INSTALL_COMMANDS = [- 'curl -fsSL https://claude.ai/install.sh | bash',- 'brew install --cask claude-code',-] as const;--export const CODEX_CLI_INSTALL_DOCS_URL =- 'https://github.com/openai/codex#installing-and-running-codex-cli';--export const CODEX_CLI_INSTALL_COMMANDS = [- 'npm install -g @openai/codex',- 'brew install --cask codex',-] as const;--export const OPENCODE_CLI_INSTALL_DOCS_URL = 'https://opencode.ai/docs';--export const OPENCODE_CLI_INSTALL_COMMANDS = [- 'curl -fsSL https://opencode.ai/install | bash',-] as const;--export const PI_CLI_INSTALL_DOCS_URL = 'https://github.com/earendil-works/pi';--export const PI_CLI_INSTALL_COMMANDS = ['npm install -g @earendil-works/pi-coding-agent'] as const;--export const QODER_CLI_AUTH_DOCS_URL = 'https://docs.qoder.com/cli/auth.md';--export const QODER_CLI_INSTALL_DOCS_URL = 'https://docs.qoder.com/cli/install.md';--export const QODER_CLI_INSTALL_COMMANDS = [- 'curl -fsSL https://qoder.com/install | bash',- 'npm install -g @qoder-ai/qodercli',-] as const;+export {+ AMP_CLI_INSTALL_COMMANDS,+ AMP_CLI_INSTALL_DOCS_URL,+ CLAUDE_CODE_CLI_INSTALL_COMMANDS,+ CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ CODEX_CLI_INSTALL_COMMANDS,+ CODEX_CLI_INSTALL_DOCS_URL,+ OPENCODE_CLI_INSTALL_COMMANDS,+ OPENCODE_CLI_INSTALL_DOCS_URL,+ PI_CLI_INSTALL_COMMANDS,+ PI_CLI_INSTALL_DOCS_URL,+ QODER_CLI_AUTH_DOCS_URL,+ QODER_CLI_INSTALL_COMMANDS,+ QODER_CLI_INSTALL_DOCS_URL,+} from '@lobechat/heterogeneous-agents';export const HeterogeneousAgentSessionErrorCode = {AuthRequired: 'auth_required',diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.jsonindex d9b78692257..2764d73887e 100644--- a/packages/heterogeneous-agents/package.json+++ b/packages/heterogeneous-agents/package.json@@ -26,12 +26,10 @@"@anthropic-ai/claude-agent-sdk": "0.3.204","@anthropic-ai/sdk": "^0.93.0","@lobechat/agent-gateway-client": "workspace:*",+ "@lobechat/types": "workspace:*","@lobehub/icons": "^5.11.0","@modelcontextprotocol/sdk": "^1.29.0","diff": "^8.0.4","zod": "^4.4.3"- },- "devDependencies": {- "@lobechat/types": "workspace:*"}}diff --git a/packages/heterogeneous-agents/src/adapters/amp.ts b/packages/heterogeneous-agents/src/adapters/amp.tsindex 43ee9c834a6..9fe8b7e6cb6 100644--- a/packages/heterogeneous-agents/src/adapters/amp.ts+++ b/packages/heterogeneous-agents/src/adapters/amp.ts@@ -1,3 +1,4 @@+import { getHeterogeneousAgentConfigOrThrow } from '../config';import { imagePlaceholder } from '../imageEcho';import type {AgentEventAdapter,@@ -15,7 +16,7 @@ import type {} from '../types';const AMP_IDENTIFIER = 'amp';-const AMP_DOCS_URL = 'https://ampcode.com/manual';+const AMP_DOCS_URL = getHeterogeneousAgentConfigOrThrow(AMP_IDENTIFIER).auth.docsUrl;interface AmpUsage {cache_creation_input_tokens?: number;diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex 80ffe7cfb0b..dd388a0effd 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -36,6 +36,7 @@* - `tool_result` blocks are in `type: 'user'` events, not assistant events*/+import { getHeterogeneousAgentConfigOrThrow } from '../config';import type { HeteroErrorKind } from '../errors/specs';import { imagePlaceholder } from '../imageEcho';import type {@@ -192,7 +193,8 @@ interface ClaudeCodeTaskEntry {subject: string;}-const CLAUDE_CODE_CLI_INSTALL_DOCS_URL = 'https://docs.anthropic.com/en/docs/claude-code/setup';+const CLAUDE_CODE_CLI_INSTALL_DOCS_URL =+ getHeterogeneousAgentConfigOrThrow('claude-code').auth.docsUrl;const CLI_AUTH_REQUIRED_PATTERNS = [/failed to authenticate/i,diff --git a/packages/heterogeneous-agents/src/adapters/opencode.ts b/packages/heterogeneous-agents/src/adapters/opencode.tsindex dab16beba67..e7ce47eaf66 100644--- a/packages/heterogeneous-agents/src/adapters/opencode.ts+++ b/packages/heterogeneous-agents/src/adapters/opencode.ts@@ -1,3 +1,4 @@+import { getHeterogeneousAgentConfigOrThrow } from '../config';import type {AgentEventAdapter,HeterogeneousAgentEvent,@@ -10,7 +11,8 @@ import type {} from '../types';const OPENCODE_IDENTIFIER = 'opencode';-const OPENCODE_CLI_INSTALL_DOCS_URL = 'https://opencode.ai/docs';+const OPENCODE_CLI_INSTALL_DOCS_URL =+ getHeterogeneousAgentConfigOrThrow(OPENCODE_IDENTIFIER).auth.docsUrl;const AUTH_REQUIRED_PATTERNS = [/authentication/i,/not authenticated/i,diff --git a/packages/heterogeneous-agents/src/adapters/pi.ts b/packages/heterogeneous-agents/src/adapters/pi.tsindex 6ec36a02502..2430e9f4cd6 100644--- a/packages/heterogeneous-agents/src/adapters/pi.ts+++ b/packages/heterogeneous-agents/src/adapters/pi.ts@@ -1,3 +1,4 @@+import { getHeterogeneousAgentConfigOrThrow } from '../config';import type {AgentEventAdapter,HeterogeneousAgentEvent,@@ -12,7 +13,7 @@ import type {} from '../types';const PI_IDENTIFIER = 'pi';-const PI_CLI_INSTALL_DOCS_URL = 'https://github.com/earendil-works/pi';+const PI_CLI_INSTALL_DOCS_URL = getHeterogeneousAgentConfigOrThrow(PI_IDENTIFIER).auth.docsUrl;const PI_AUTH_REQUIRED_PATTERNS = [/failed to authenticate/i,/invalid (?:authentication )?(?:credentials?|tokens?|api keys?)/i,diff --git a/packages/heterogeneous-agents/src/adapters/qoder.ts b/packages/heterogeneous-agents/src/adapters/qoder.tsindex 1fee93f0e81..c8bba4a1a7e 100644--- a/packages/heterogeneous-agents/src/adapters/qoder.ts+++ b/packages/heterogeneous-agents/src/adapters/qoder.ts@@ -7,13 +7,14 @@* tool payload, error, and usage record is stamped with Qoder's identity.*/+import { getHeterogeneousAgentConfigOrThrow } from '../config';import type { HeterogeneousAgentEvent } from '../types';import { ClaudeCodeAdapter } from './claudeCode';export const QODER_IDENTIFIER = 'qoder';-const CLAUDE_CODE_AUTH_DOCS_URL = 'https://docs.anthropic.com/en/docs/claude-code/setup';-const QODER_AUTH_DOCS_URL = 'https://docs.qoder.com/cli/auth.md';+const CLAUDE_CODE_AUTH_DOCS_URL = getHeterogeneousAgentConfigOrThrow('claude-code').auth.docsUrl;+const QODER_AUTH_DOCS_URL = getHeterogeneousAgentConfigOrThrow(QODER_IDENTIFIER).auth.docsUrl;const QODER_AUTH_REQUIRED_PATTERNS = [/not logged in/i, /please run \/login/i] as const;const isQoderAuthAssistant = (raw: unknown): boolean => {diff --git a/packages/heterogeneous-agents/src/client/index.ts b/packages/heterogeneous-agents/src/client/index.tsindex deb51c7b7b9..64f00132f2c 100644--- a/packages/heterogeneous-agents/src/client/index.ts+++ b/packages/heterogeneous-agents/src/client/index.ts@@ -4,16 +4,15 @@ import { Amp, ClaudeCode, Codex, getLobeIconCDN, OpenCode, Pi, Qoder } from '@loimport {getHeterogeneousAgentConfig,HETEROGENEOUS_AGENT_CONFIGS,- type HeterogeneousAgentConfig,isRemoteHeterogeneousType,} from '../config';export { isRemoteHeterogeneousType };-export interface HeterogeneousAgentClientConfig extends HeterogeneousAgentConfig {+export type HeterogeneousAgentClientConfig = (typeof HETEROGENEOUS_AGENT_CONFIGS)[number] & {avatar: string;icon: IconType;-}+};const heterogeneousAgentIcons = {'amp': Amp,@@ -22,7 +21,7 @@ const heterogeneousAgentIcons = {'opencode': OpenCode,'pi': Pi,'qoder': Qoder,-} as const satisfies Record<HeterogeneousAgentConfig['type'], IconType>;+} as const satisfies Record<HeterogeneousAgentClientConfig['type'], IconType>;const createAgentAvatar = (iconId: string) =>getLobeIconCDN(iconId, {diff --git a/packages/heterogeneous-agents/src/config.test.ts b/packages/heterogeneous-agents/src/config.test.tsindex 84da4bac476..c1035a23a3f 100644--- a/packages/heterogeneous-agents/src/config.test.ts+++ b/packages/heterogeneous-agents/src/config.test.ts@@ -1,9 +1,12 @@import { describe, expect, it } from 'vitest';import {+ buildHeterogeneousAgentAuthRequiredError,getHeterogeneousAgentConfig,HETEROGENEOUS_AGENT_CONFIGS,+ isHeterogeneousAgentAuthRequired,isRemoteHeterogeneousType,+ resolveHeterogeneousAgentCommand,} from './config';import { HETEROGENEOUS_TYPE_LABELS } from './labels';@@ -19,39 +22,63 @@ describe('heterogeneous agent config', () => {]);});- it('resolves config by type', () => {+ it('resolves descriptor metadata by type', () => {expect(getHeterogeneousAgentConfig('claude-code')).toMatchObject({- command: 'claude',+ defaultCommand: 'claude',+ install: {+ docsUrl: 'https://docs.anthropic.com/en/docs/claude-code/setup',+ },+ kind: 'local-cli',title: 'Claude Code',type: 'claude-code',});expect(getHeterogeneousAgentConfig('codex')).toMatchObject({- command: 'codex',+ defaultCommand: 'codex',title: 'Codex',type: 'codex',});expect(getHeterogeneousAgentConfig('amp')).toMatchObject({- command: 'amp',+ defaultCommand: 'amp',title: 'Amp',type: 'amp',});expect(getHeterogeneousAgentConfig('opencode')).toMatchObject({- command: 'opencode',+ defaultCommand: 'opencode',title: 'OpenCode',type: 'opencode',});expect(getHeterogeneousAgentConfig('pi')).toMatchObject({- command: 'pi',+ defaultCommand: 'pi',title: 'Pi',type: 'pi',});expect(getHeterogeneousAgentConfig('qoder')).toMatchObject({- command: 'qodercli',+ auth: { docsUrl: 'https://docs.qoder.com/cli/auth.md' },+ defaultCommand: 'qodercli',title: 'Qoder',type: 'qoder',});});+ it('resolves commands from descriptors and fails loudly for unknown types', () => {+ expect(resolveHeterogeneousAgentCommand('claude-code')).toBe('claude');+ expect(resolveHeterogeneousAgentCommand('claude-code', ' claude-beta ')).toBe('claude-beta');+ expect(() => resolveHeterogeneousAgentCommand('unknown-agent')).toThrow(+ 'Unknown local heterogeneous agent type: "unknown-agent"',+ );+ });++ it('builds auth guidance from descriptor metadata', () => {+ expect(isHeterogeneousAgentAuthRequired('amp', 'Please log in before continuing')).toBe(true);+ expect(buildHeterogeneousAgentAuthRequiredError({ agentType: 'amp' })).toMatchObject({+ agentType: 'amp',+ code: 'auth_required',+ command: 'amp',+ docsUrl: 'https://ampcode.com/manual',+ message: 'Amp could not authenticate. Run `amp login` or configure AMP_API_KEY, then retry.',+ });+ });+it('derives display labels from the shared config source', () => {expect(HETEROGENEOUS_TYPE_LABELS).toEqual({'amp': 'Amp',diff --git a/packages/heterogeneous-agents/src/config.ts b/packages/heterogeneous-agents/src/config.tsindex 5d99feb7229..d218a505319 100644--- a/packages/heterogeneous-agents/src/config.ts+++ b/packages/heterogeneous-agents/src/config.ts@@ -1,108 +1,145 @@-export type HeterogeneousAgentMenuLabelKey =- | 'newAmpAgent'- | 'newClaudeCodeAgent'- | 'newCodexAgent'- | 'newOpenCodeAgent'- | 'newPiAgent'- | 'newQoderAgent';--/**- * Config for local CLI hetero agents (Amp, Claude Code, Codex, OpenCode, Pi, Qoder) that run as- * desktop subprocesses via Electron IPC. Platform task agents (openclaw,- * hermes) use a separate notify-based runner and are not listed here.- */-export interface HeterogeneousAgentConfig {- command: string;- iconId: string;- menuKey: string;- menuLabelKey: HeterogeneousAgentMenuLabelKey;- title: string;- type: 'amp' | 'claude-code' | 'codex' | 'opencode' | 'pi' | 'qoder';-}+import type {+ HeterogeneousAgentDescriptor,+ HeterogeneousAgentMenuLabelKey,+ HeterogeneousAgentType,+ LocalHeterogeneousAgentDescriptor,+ LocalHeterogeneousAgentType,+ RemoteHeterogeneousAgentDescriptor,+ RemoteHeterogeneousAgentType,+} from '@lobechat/types';+import { HETEROGENEOUS_AGENT_CONFIGS, REMOTE_HETEROGENEOUS_AGENT_CONFIGS } from '@lobechat/types';++export type {+ HeterogeneousAgentDescriptor,+ HeterogeneousAgentMenuLabelKey,+ HeterogeneousAgentType,+ LocalHeterogeneousAgentDescriptor,+ LocalHeterogeneousAgentType,+ RemoteHeterogeneousAgentDescriptor,+ RemoteHeterogeneousAgentType,+};+export { HETEROGENEOUS_AGENT_CONFIGS, REMOTE_HETEROGENEOUS_AGENT_CONFIGS };++/** @deprecated Use `LocalHeterogeneousAgentDescriptor`. */+export type HeterogeneousAgentConfig = LocalHeterogeneousAgentDescriptor;+/** @deprecated Use `RemoteHeterogeneousAgentDescriptor`. */+export type RemoteHeterogeneousAgentConfig = RemoteHeterogeneousAgentDescriptor;++export const LOCAL_HETEROGENEOUS_AGENT_TYPES = HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type);-export const HETEROGENEOUS_AGENT_CONFIGS = [- {- command: 'amp',- iconId: 'Amp',- menuKey: 'newAmpAgent',- menuLabelKey: 'newAmpAgent',- title: 'Amp',- type: 'amp',- },- {- command: 'claude',- iconId: 'ClaudeCode',- menuKey: 'newClaudeCodeAgent',- menuLabelKey: 'newClaudeCodeAgent',- title: 'Claude Code',- type: 'claude-code',- },- {- command: 'codex',- iconId: 'Codex',- menuKey: 'newCodexAgent',- menuLabelKey: 'newCodexAgent',- title: 'Codex',- type: 'codex',- },- {- command: 'opencode',- iconId: 'OpenCode',- menuKey: 'newOpenCodeAgent',- menuLabelKey: 'newOpenCodeAgent',- title: 'OpenCode',- type: 'opencode',- },- {- command: 'pi',- iconId: 'Pi',- menuKey: 'newPiAgent',- menuLabelKey: 'newPiAgent',- title: 'Pi',- type: 'pi',- },- {- command: 'qodercli',- iconId: 'Qoder',- menuKey: 'newQoderAgent',- menuLabelKey: 'newQoderAgent',- title: 'Qoder',- type: 'qoder',- },-] as const satisfies readonly HeterogeneousAgentConfig[];+const LOCAL_HETERO_TYPES = new Set<string>(LOCAL_HETEROGENEOUS_AGENT_TYPES);+const REMOTE_HETERO_TYPES = new Set<string>(+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),+);++export const isLocalHeterogeneousType = (type: string): type is LocalHeterogeneousAgentType =>+ LOCAL_HETERO_TYPES.has(type);++export const isRemoteHeterogeneousType = (type: string): type is RemoteHeterogeneousAgentType =>+ REMOTE_HETERO_TYPES.has(type);export const getHeterogeneousAgentConfig = (type: string) =>HETEROGENEOUS_AGENT_CONFIGS.find((config) => config.type === type);-/**- * Config for platform task hetero agents that communicate back via- * agentNotify.notify. They can run on this desktop or a connected device,- * but use a different execution protocol from local CLI stream adapters.- * Add new remote platform types here to automatically propagate display- * names across the UI (model tag, loading indicator, agent list, etc.).- */-export interface RemoteHeterogeneousAgentConfig {- title: string;- type: 'hermes' | 'openclaw';+export const getHeterogeneousAgentConfigOrThrow = (+ type: string,+): (typeof HETEROGENEOUS_AGENT_CONFIGS)[number] => {+ const config = getHeterogeneousAgentConfig(type);+ if (!config) throw new Error(`Unknown local heterogeneous agent type: "${type}"`);+ return config;+};++export const resolveHeterogeneousAgentCommand = (type: string, command?: string): string => {+ const configuredCommand = command?.trim();+ return configuredCommand || getHeterogeneousAgentConfigOrThrow(type).defaultCommand;+};++export interface HeterogeneousAgentCliError {+ agentType: LocalHeterogeneousAgentType;+ code: 'auth_required' | 'cli_not_found';+ command: string;+ docsUrl: string;+ installCommands?: readonly string[];+ message: string;+ stderr?: string;}-export const REMOTE_HETEROGENEOUS_AGENT_CONFIGS = [- { title: 'OpenClaw', type: 'openclaw' },- { title: 'Hermes', type: 'hermes' },-] as const satisfies readonly RemoteHeterogeneousAgentConfig[];+interface BuildHeterogeneousAgentCliErrorOptions {+ agentType: string;+ command?: string;+ stderr?: string;+}-/** Union of all local CLI hetero types. */-export type LocalHeterogeneousAgentType = (typeof HETEROGENEOUS_AGENT_CONFIGS)[number]['type'];+export const buildHeterogeneousAgentCliNotFoundError = ({+ agentType,+ command,+ stderr,+}: BuildHeterogeneousAgentCliErrorOptions): HeterogeneousAgentCliError => {+ const descriptor = getHeterogeneousAgentConfigOrThrow(agentType);+ const resolvedCommand = resolveHeterogeneousAgentCommand(agentType, command);-/** Union of all notify-based platform task hetero types. */-export type RemoteHeterogeneousAgentType =- (typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number]['type'];+ return {+ agentType: descriptor.type,+ code: 'cli_not_found',+ command: resolvedCommand,+ docsUrl: descriptor.install.docsUrl,+ installCommands: descriptor.install.commands,+ message: `${descriptor.title} CLI was not found. Install it and make sure \`${resolvedCommand}\` can be executed.`,+ ...(stderr ? { stderr } : {}),+ };+};-/** Union of every supported hetero agent type. */-export type HeterogeneousAgentType = LocalHeterogeneousAgentType | RemoteHeterogeneousAgentType;+export const buildHeterogeneousAgentAuthRequiredError = ({+ agentType,+ command,+ stderr,+}: BuildHeterogeneousAgentCliErrorOptions): HeterogeneousAgentCliError => {+ const descriptor = getHeterogeneousAgentConfigOrThrow(agentType);-const REMOTE_HETERO_TYPES = new Set<string>(REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((c) => c.type));+ return {+ agentType: descriptor.type,+ code: 'auth_required',+ command: resolveHeterogeneousAgentCommand(agentType, command),+ docsUrl: descriptor.auth.docsUrl,+ message: descriptor.auth.errorMessage,+ ...(stderr ? { stderr } : {}),+ };+};-/** Returns true when `type` identifies a notify-based platform agent. */-export const isRemoteHeterogeneousType = (type: string): type is RemoteHeterogeneousAgentType =>- REMOTE_HETERO_TYPES.has(type);+const AUTH_REQUIRED_PATTERNS = new Map<LocalHeterogeneousAgentType, readonly RegExp[]>();++export const isHeterogeneousAgentAuthRequired = (agentType: string, detail: string): boolean => {+ const descriptor = getHeterogeneousAgentConfig(agentType);+ if (!descriptor) return false;++ let patterns = AUTH_REQUIRED_PATTERNS.get(descriptor.type);+ if (!patterns) {+ patterns = descriptor.auth.patterns.map((source) => new RegExp(source, 'i'));+ AUTH_REQUIRED_PATTERNS.set(descriptor.type, patterns);+ }++ return patterns.some((pattern) => pattern.test(detail));+};++// Compatibility exports for existing IPC consumers. Values are derived from+// the descriptor catalog rather than maintained as a second metadata table.+const ampDescriptor = getHeterogeneousAgentConfigOrThrow('amp');+const claudeCodeDescriptor = getHeterogeneousAgentConfigOrThrow('claude-code');+const codexDescriptor = getHeterogeneousAgentConfigOrThrow('codex');+const openCodeDescriptor = getHeterogeneousAgentConfigOrThrow('opencode');+const piDescriptor = getHeterogeneousAgentConfigOrThrow('pi');+const qoderDescriptor = getHeterogeneousAgentConfigOrThrow('qoder');++export const AMP_CLI_INSTALL_COMMANDS = ampDescriptor.install.commands;+export const AMP_CLI_INSTALL_DOCS_URL = ampDescriptor.install.docsUrl;+export const CLAUDE_CODE_CLI_INSTALL_COMMANDS = claudeCodeDescriptor.install.commands;+export const CLAUDE_CODE_CLI_INSTALL_DOCS_URL = claudeCodeDescriptor.install.docsUrl;+export const CODEX_CLI_INSTALL_COMMANDS = codexDescriptor.install.commands;+export const CODEX_CLI_INSTALL_DOCS_URL = codexDescriptor.install.docsUrl;+export const OPENCODE_CLI_INSTALL_COMMANDS = openCodeDescriptor.install.commands;+export const OPENCODE_CLI_INSTALL_DOCS_URL = openCodeDescriptor.install.docsUrl;+export const PI_CLI_INSTALL_COMMANDS = piDescriptor.install.commands;+export const PI_CLI_INSTALL_DOCS_URL = piDescriptor.install.docsUrl;+export const QODER_CLI_AUTH_DOCS_URL = qoderDescriptor.auth.docsUrl;+export const QODER_CLI_INSTALL_COMMANDS = qoderDescriptor.install.commands;+export const QODER_CLI_INSTALL_DOCS_URL = qoderDescriptor.install.docsUrl;diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex abf24445298..9b181acaace 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -1,14 +1,39 @@export { AmpAdapter, ClaudeCodeAdapter, QoderAdapter } from './adapters';export type {+ HeterogeneousAgentCliError,+ HeterogeneousAgentDescriptor,+ HeterogeneousAgentMenuLabelKey,HeterogeneousAgentType,+ LocalHeterogeneousAgentDescriptor,LocalHeterogeneousAgentType,+ RemoteHeterogeneousAgentDescriptor,RemoteHeterogeneousAgentType,} from './config';export {+ AMP_CLI_INSTALL_COMMANDS,+ AMP_CLI_INSTALL_DOCS_URL,+ buildHeterogeneousAgentAuthRequiredError,+ buildHeterogeneousAgentCliNotFoundError,+ CLAUDE_CODE_CLI_INSTALL_COMMANDS,+ CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ CODEX_CLI_INSTALL_COMMANDS,+ CODEX_CLI_INSTALL_DOCS_URL,getHeterogeneousAgentConfig,+ getHeterogeneousAgentConfigOrThrow,HETEROGENEOUS_AGENT_CONFIGS,+ isHeterogeneousAgentAuthRequired,+ isLocalHeterogeneousType,isRemoteHeterogeneousType,+ LOCAL_HETEROGENEOUS_AGENT_TYPES,+ OPENCODE_CLI_INSTALL_COMMANDS,+ OPENCODE_CLI_INSTALL_DOCS_URL,+ PI_CLI_INSTALL_COMMANDS,+ PI_CLI_INSTALL_DOCS_URL,+ QODER_CLI_AUTH_DOCS_URL,+ QODER_CLI_INSTALL_COMMANDS,+ QODER_CLI_INSTALL_DOCS_URL,REMOTE_HETEROGENEOUS_AGENT_CONFIGS,+ resolveHeterogeneousAgentCommand,} from './config';export type {HeteroErrorAttribution,@@ -41,7 +66,7 @@ export type {SetErrorIntent,} from './mainAgentCoordinator';export { createMainAgentRunState, reduceMainAgent } from './mainAgentCoordinator';-export { createAdapter, listAgentTypes } from './registry';+export { createAdapter, listAgentTypes, listLocalAgentTypes } from './registry';export type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './scan/types';export { isHeteroStatusGuideErrorData } from './spawn/classifyProcessFailure';export type {diff --git a/packages/heterogeneous-agents/src/registry.test.ts b/packages/heterogeneous-agents/src/registry.test.tsindex 3f8d5a158b5..164a09642e5 100644--- a/packages/heterogeneous-agents/src/registry.test.ts+++ b/packages/heterogeneous-agents/src/registry.test.ts@@ -8,7 +8,8 @@ import {PiAdapter,QoderAdapter,} from './adapters';-import { createAdapter, listAgentTypes } from './registry';+import { HETEROGENEOUS_AGENT_CONFIGS } from './config';+import { createAdapter, listAgentTypes, listLocalAgentTypes } from './registry';describe('registry', () => {describe('createAdapter', () => {@@ -45,14 +46,11 @@ describe('registry', () => {});describe('listAgentTypes', () => {- it('includes every local CLI adapter', () => {- const types = listAgentTypes();- expect(types).toContain('amp');- expect(types).toContain('claude-code');- expect(types).toContain('codex');- expect(types).toContain('opencode');- expect(types).toContain('pi');- expect(types).toContain('qoder');+ it('registers exactly one local adapter for every descriptor', () => {+ expect(listLocalAgentTypes().toSorted()).toEqual(+ HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type).toSorted(),+ );+ expect(listAgentTypes()).toContain('claude-code-sdk');});});});diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.tsindex 99ccc35fab3..7b6a20d5124 100644--- a/packages/heterogeneous-agents/src/registry.ts+++ b/packages/heterogeneous-agents/src/registry.ts@@ -14,22 +14,20 @@ import {PiAdapter,QoderAdapter,} from './adapters';+import type { LocalHeterogeneousAgentType } from './config';import type { AgentEventAdapter } from './types';interface AgentRegistryEntry {createAdapter: () => AgentEventAdapter;}-const registry: Record<string, AgentRegistryEntry> = {+const localAgentRegistry = {'amp': {createAdapter: () => new AmpAdapter(),},'claude-code': {createAdapter: () => new ClaudeCodeAdapter(),},- 'claude-code-sdk': {- createAdapter: () => new ClaudeCodeSdkAdapter(),- },'codex': {createAdapter: () => new CodexAdapter(),},@@ -43,6 +41,17 @@ const registry: Record<string, AgentRegistryEntry> = {createAdapter: () => new QoderAdapter(),},// 'kimi-cli': { createAdapter: () => new KimiCLIAdapter() },+} satisfies Record<LocalHeterogeneousAgentType, AgentRegistryEntry>;++const runtimeAdapterRegistry = {+ 'claude-code-sdk': {+ createAdapter: () => new ClaudeCodeSdkAdapter(),+ },+} satisfies Record<string, AgentRegistryEntry>;++const registry: Record<string, AgentRegistryEntry> = {+ ...localAgentRegistry,+ ...runtimeAdapterRegistry,};/**@@ -62,3 +71,7 @@ export const createAdapter = (agentType: string): AgentEventAdapter => {* List all registered agent types.*/export const listAgentTypes = (): string[] => Object.keys(registry);++/** Local CLI adapters that must match the shared descriptor catalog. */+export const listLocalAgentTypes = (): LocalHeterogeneousAgentType[] =>+ Object.keys(localAgentRegistry) as LocalHeterogeneousAgentType[];diff --git a/packages/heterogeneous-agents/src/scan/scanHost.ts b/packages/heterogeneous-agents/src/scan/scanHost.tsindex 0d6a291297a..adb6e41df3c 100644--- a/packages/heterogeneous-agents/src/scan/scanHost.ts+++ b/packages/heterogeneous-agents/src/scan/scanHost.ts@@ -54,7 +54,7 @@ export const probeRemotePlatform = async (export const scanHeterogeneousAgentsOnHost = async (): Promise<HeterogeneousAgentScanMap> => {const entries = await Promise.all([...HETEROGENEOUS_AGENT_CONFIGS.map(async (config) => {- const status = await detectHeterogeneousCliCommand(config.type, config.command);+ const status = await detectHeterogeneousCliCommand(config.type, config.defaultCommand);return [config.type,{diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.tsindex 10c860fe64f..0a8712161c4 100644--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts@@ -88,6 +88,18 @@ describe('classifyHeteroProcessFailure', () => {expect(result?.message).toContain('`codex`');});+ it('preserves a configured command in CLI-not-found guidance', () => {+ const result = classifyHeteroProcessFailure({+ agentType: 'claude-code',+ command: '/opt/bin/claude-beta',+ detail: 'Error: spawn /opt/bin/claude-beta ENOENT',+ errnoCode: 'ENOENT',+ });++ expect(result).toMatchObject({ command: '/opt/bin/claude-beta' });+ expect(result?.message).toContain('`/opt/bin/claude-beta`');+ });+it('classifies a missing OpenCode binary for the install guide', () => {const result = classifyHeteroProcessFailure({agentType: 'opencode',@@ -177,13 +189,35 @@ describe('classifyHeteroProcessFailure', () => {expect(result?.code).toBe('cli_not_found');});- it('returns undefined for unsupported agent types', () => {+ it('classifies missing and unauthenticated Amp installations', () => {expect(classifyHeteroProcessFailure({agentType: 'amp',detail: 'Error: spawn amp ENOENT',errnoCode: 'ENOENT',}),+ ).toMatchObject({+ agentType: 'amp',+ code: 'cli_not_found',+ command: 'amp',+ docsUrl: 'https://ampcode.com/manual',+ });++ expect(+ classifyHeteroProcessFailure({+ agentType: 'amp',+ detail: 'Please log in with `amp login` or configure AMP_API_KEY.',+ }),+ ).toMatchObject({ agentType: 'amp', code: 'auth_required', command: 'amp' });+ });++ it('returns undefined for unsupported agent types', () => {+ expect(+ classifyHeteroProcessFailure({+ agentType: 'kimi-cli',+ detail: 'Error: spawn kimi ENOENT',+ errnoCode: 'ENOENT',+ }),).toBeUndefined();});diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.tsindex cc9c426836c..e4cabbdd685 100644--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts@@ -1,3 +1,10 @@+import {+ buildHeterogeneousAgentAuthRequiredError,+ buildHeterogeneousAgentCliNotFoundError,+ HETEROGENEOUS_AGENT_CONFIGS,+ isHeterogeneousAgentAuthRequired,+ isLocalHeterogeneousType,+} from '../config';import type { HeterogeneousTerminalErrorData } from '../types';/**@@ -29,43 +36,6 @@ import type { HeterogeneousTerminalErrorData } from '../types';*/const SPAWN_ENOENT_PATTERN = /\bspawn .+ ENOENT\b/;-/** Mirrors `CLI_AUTH_REQUIRED_PATTERNS` in the desktop `HeterogeneousAgentCtr`. */-const CLI_AUTH_REQUIRED_PATTERNS = [- /failed to authenticate/i,- /invalid authentication credentials/i,- /authentication[_ ]error/i,- /not authenticated/i,- /\bunauthorized\b/i,- /\b401\b/,- /no api key found/i,- /no models available/i,-] as const;-const QODER_AUTH_REQUIRED_PATTERNS = [/not logged in/i, /please run \/login/i] as const;--const CLI_NOT_FOUND_MESSAGES: Record<string, string> = {- 'claude-code':- 'Claude Code CLI was not found on the machine running this agent. Install it and make sure `claude` can be executed.',- 'codex':- 'Codex CLI was not found on the machine running this agent. Install it and make sure `codex` can be executed.',- 'opencode':- 'OpenCode CLI was not found on the machine running this agent. Install it and make sure `opencode` can be executed.',- 'pi': 'Pi CLI was not found on the machine running this agent. Install it and make sure `pi` can be executed.',- 'qoder':- 'Qoder CLI was not found on the machine running this agent. Install it and make sure `qodercli` can be executed.',-};--const AUTH_REQUIRED_MESSAGES: Record<string, string> = {- 'claude-code':- 'Claude Code could not authenticate on the machine running this agent. Sign in again or refresh its credentials, then retry.',- 'codex':- 'Codex could not authenticate on the machine running this agent. Sign in again or refresh its credentials, then retry.',- 'opencode':- 'OpenCode could not authenticate on the machine running this agent. Sign in again or refresh its credentials, then retry.',- 'pi': 'Pi could not authenticate on the machine running this agent. Run `pi`, use `/login`, then retry.',- 'qoder':- 'Qoder could not authenticate on the machine running this agent. Run `qodercli login`, then retry.',-};-/*** Codes/agent types the client renders the dedicated status-guide card for.* Must stay in sync with `HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES` in@@ -78,14 +48,9 @@ const STATUS_GUIDE_ERROR_CODES = new Set(['overloaded','rate_limit',]);-const STATUS_GUIDE_AGENT_TYPES = new Set([- 'amp',- 'claude-code',- 'codex',- 'opencode',- 'pi',- 'qoder',-]);+const STATUS_GUIDE_AGENT_TYPES = new Set(+ HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type as string),+);/*** Whether a terminal error payload (an adapter's in-stream `error` event data,@@ -110,6 +75,8 @@ export const isHeteroStatusGuideErrorData = (export interface ClassifyHeteroProcessFailureParams {/** Adapter type key for a local CLI with a status guide. */agentType: string;+ /** Configured CLI command, when the caller overrides the descriptor default. */+ command?: string;/** Stderr tail / flattened error message to pattern-match. */detail?: string;/**@@ -127,32 +94,25 @@ export interface ClassifyHeteroProcessFailureParams {export const classifyHeteroProcessFailure = (params: ClassifyHeteroProcessFailureParams,): HeterogeneousTerminalErrorData | undefined => {- const { agentType, errnoCode } = params;+ const { agentType, command, errnoCode } = params;const detail = params.detail?.trim();- const cliNotFoundMessage = CLI_NOT_FOUND_MESSAGES[agentType];// Unknown agent type → the client guide can't render it; don't classify.- if (!cliNotFoundMessage) return;+ if (!isLocalHeterogeneousType(agentType)) return;if (errnoCode === 'ENOENT' || (detail && SPAWN_ENOENT_PATTERN.test(detail))) {- return {+ return buildHeterogeneousAgentCliNotFoundError({agentType,- code: 'cli_not_found',- message: cliNotFoundMessage,- ...(detail ? { stderr: detail } : {}),- };+ command,+ stderr: detail,+ });}- const authRequiredPatterns =- agentType === 'qoder'- ? [...CLI_AUTH_REQUIRED_PATTERNS, ...QODER_AUTH_REQUIRED_PATTERNS]- : CLI_AUTH_REQUIRED_PATTERNS;- if (detail && authRequiredPatterns.some((pattern) => pattern.test(detail))) {- return {+ if (detail && isHeterogeneousAgentAuthRequired(agentType, detail)) {+ return buildHeterogeneousAgentAuthRequiredError({agentType,- code: 'auth_required',- message: AUTH_REQUIRED_MESSAGES[agentType],+ command,stderr: detail,- };+ });}};diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex 39c3ae78295..28b65b73161 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -3,6 +3,9 @@ import { homedir, platform } from 'node:os';import path from 'node:path';import { promisify } from 'node:util';+import type { LocalHeterogeneousAgentType } from '../config';+import { HETEROGENEOUS_AGENT_CONFIGS } from '../config';+/*** Shared resolver for external CLI-agent binaries (Amp / Claude Code / Codex / OpenCode / Pi / Qoder).*@@ -20,8 +23,7 @@ import { promisify } from 'node:util';const execFilePromise = promisify(execFile);const execPromise = promisify(exec);-export type HeterogeneousCliAgentType =- 'amp' | 'claude-code' | 'codex' | 'opencode' | 'pi' | 'qoder';+export type HeterogeneousCliAgentType = LocalHeterogeneousAgentType;/*** Resolution result. A structural subset of the desktop `BinaryManager`'s@@ -274,14 +276,9 @@ const HETEROGENEOUS_CLI_AGENT_OPTIONS = {// The default (bare) command each agent type is shipped to run. The well-known// fallback locations below hold *this* binary, so they may only be probed when// the requested command is the default — never for a custom command.-export const DEFAULT_HETERO_COMMAND: Record<HeterogeneousCliAgentType, string> = {- 'amp': 'amp',- 'claude-code': 'claude',- 'codex': 'codex',- 'opencode': 'opencode',- 'pi': 'pi',- 'qoder': 'qodercli',-};+export const DEFAULT_HETERO_COMMAND = Object.fromEntries(+ HETEROGENEOUS_AGENT_CONFIGS.map(({ defaultCommand, type }) => [type, defaultCommand]),+) as Record<HeterogeneousCliAgentType, string>;// Well-known absolute install locations probed when a bare command isn't on// PATH. This covers GUI-launched apps with a lean launchd PATH: Claude'sdiff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.tsindex e60db7e4a31..1aefd2ea8a7 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts@@ -565,7 +565,7 @@ describe('spawnAgent', () => {const { spawnAgent } = await import('./spawnAgent');await expect(spawnAgent({ agentType: 'kimi-cli', operationId: 'op-1', prompt: 'hi' }),- ).rejects.toThrow(/unsupported agent type/);+ ).rejects.toThrow('Unknown local heterogeneous agent type: "kimi-cli"');});it('events iterator drains all pipeline events including the trailing flush', async () => {diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 096b4815bd2..54bcedf47ad 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -3,6 +3,7 @@ import { spawn } from 'node:child_process';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { resolveHeterogeneousAgentCommand } from '../config';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';import { resolveCliSpawnPlan } from './cliSpawn';import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';@@ -294,29 +295,6 @@ const buildSpawnArgs = (params: BuildSpawnArgsParams): string[] => {}};-const defaultCommand = (agentType: string): string => {- switch (agentType) {- case 'amp': {- return 'amp';- }- case 'codex': {- return 'codex';- }- case 'opencode': {- return 'opencode';- }- case 'pi': {- return 'pi';- }- case 'qoder': {- return 'qodercli';- }- default: {- return 'claude';- }- }-};-const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {if (!proc.pid || proc.killed) return;@@ -359,7 +337,7 @@ const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {* failed image fetch surfaces before the child starts.*/export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentHandle> => {- const command = options.command || defaultCommand(options.agentType);+ const command = resolveHeterogeneousAgentCommand(options.agentType, options.command);const inputPlan = await buildAgentInput(options.agentType, options.prompt, options.inputOptions);const args = buildSpawnArgs({agentType: options.agentType,diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.tsindex ec707905131..221e339cbbe 100644--- a/packages/heterogeneous-agents/src/types.ts+++ b/packages/heterogeneous-agents/src/types.ts@@ -351,6 +351,7 @@ export interface HeterogeneousTerminalErrorData {agentType?: string;clearEchoedContent?: boolean;code?: string;+ command?: string;/*** Diagnostic context from the CLI's terminal event (subtype, HTTP status,* turn count, session id, …). Persisted verbatim into the error body so thediff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.tsindex 7bb2304894c..40775e91a2a 100644--- a/packages/types/src/agent/agencyConfig.test.ts+++ b/packages/types/src/agent/agencyConfig.test.ts@@ -8,6 +8,7 @@ import {codexModelSupportsReasoningEffort,getCodexReasoningEffortLevels,HETEROGENEOUS_AGENT_DEFAULT_SELECTION,+ normalizeHeterogeneousProviderConfig,pruneWorkingDirByDeviceDeletes,resolveAgencyConfig,resolveAgentAgencyConfig,@@ -18,6 +19,38 @@ import {resolveCodexSpeedMode,} from './agencyConfig';+describe('normalizeHeterogeneousProviderConfig', () => {+ it('recovers a legacy adapterType before considering the command', () => {+ const legacyConfig = {+ adapterType: 'codex',+ command: 'claude',+ } as unknown as HeterogeneousProviderConfig;++ expect(normalizeHeterogeneousProviderConfig(legacyConfig)).toEqual({+ command: 'claude',+ type: 'codex',+ });+ });++ it('infers legacy Claude Code and Codex identities from their commands', () => {+ const legacyClaudeConfig = {+ command: '/usr/local/bin/custom-claude',+ } as unknown as HeterogeneousProviderConfig;+ const legacyCodexConfig = {+ command: '/usr/local/bin/custom-codex',+ } as unknown as HeterogeneousProviderConfig;++ expect(normalizeHeterogeneousProviderConfig(legacyClaudeConfig).type).toBe('claude-code');+ expect(normalizeHeterogeneousProviderConfig(legacyCodexConfig).type).toBe('codex');+ });++ it('preserves the legacy Claude Code default when no identity can be recovered', () => {+ const legacyConfig = { command: 'custom-agent' } as unknown as HeterogeneousProviderConfig;++ expect(normalizeHeterogeneousProviderConfig(legacyConfig).type).toBe('claude-code');+ });+});+describe('pruneWorkingDirByDeviceDeletes', () => {it('deletes keys whose patch value is undefined', () => {const merged = { workingDirByDevice: { 'device-a': '/a', 'device-b': '/b' } };@@ -507,6 +540,18 @@ describe('codex speed mode', () => {});describe('resolveAgencyConfig', () => {+ it('normalizes a legacy persisted heterogeneous provider before applying overrides', () => {+ const shared = {+ executionTarget: 'device',+ heterogeneousProvider: { command: 'codex' },+ } as unknown as Parameters<typeof resolveAgencyConfig>[0];++ expect(resolveAgencyConfig(shared, { executionTarget: 'local' })).toEqual({+ executionTarget: 'local',+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ });+ });+it('ignores a member override when the shared execution target is fixed', () => {const shared = {boundDeviceId: 'fixed-device',diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex 29406d10997..8fa6366f715 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -1,5 +1,10 @@import type { WorkingDirConfigValue } from '../device';import type { LobeAgentChatConfig } from './chatConfig';+import type { HeterogeneousAgentType, LocalHeterogeneousAgentType } from './heterogeneousAgent';+import {+ HETEROGENEOUS_AGENT_CONFIGS,+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS,+} from './heterogeneousAgent';/*** Selector value that means "do not override the underlying CLI".@@ -190,10 +195,77 @@ export interface HeterogeneousProviderConfig {* Combined with any runtime-generated context (e.g. cloned repo list).*/systemContext?: string;- /** Agent runtime type. */- type: 'amp' | 'claude-code' | 'codex' | 'hermes' | 'opencode' | 'openclaw' | 'pi' | 'qoder';+ /** Agent runtime type, derived from the shared heterogeneous-agent descriptor catalog. */+ type: HeterogeneousAgentType;}+const HETEROGENEOUS_AGENT_TYPES = new Set<string>([+ ...HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),+ ...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),+]);++const LEGACY_COMMAND_INFERENCE_TYPES = new Set<LocalHeterogeneousAgentType>([+ 'claude-code',+ 'codex',+]);++interface LegacyHeterogeneousProviderConfig extends HeterogeneousProviderConfig {+ adapterType?: unknown;+}++const resolveKnownHeterogeneousAgentType = (value: unknown): HeterogeneousAgentType | undefined => {+ if (typeof value !== 'string' || !value) return;+ if (!HETEROGENEOUS_AGENT_TYPES.has(value)) {+ throw new Error(`Unknown heterogeneous agent type: "${value}"`);+ }+ return value as HeterogeneousAgentType;+};++/**+ * Upgrade a persisted provider config written before `type` became required.+ *+ * New callers must always write `type`; this compatibility path exists because+ * `agents.agency_config` is JSONB and older rows are not runtime-schema parsed+ * or backfilled. The old renderer preferred `adapterType`, then recognized+ * Claude/Codex from `command`, and otherwise defaulted to Claude Code.+ */+export const normalizeHeterogeneousProviderConfig = (+ config: HeterogeneousProviderConfig,+): HeterogeneousProviderConfig => {+ const legacyConfig = config as LegacyHeterogeneousProviderConfig;+ const explicitType = resolveKnownHeterogeneousAgentType(legacyConfig.type);+ if (explicitType && legacyConfig.adapterType === undefined) return config;++ const adapterType = explicitType+ ? undefined+ : resolveKnownHeterogeneousAgentType(legacyConfig.adapterType);+ const normalizedCommand = config.command?.trim().toLowerCase();+ const inferredType = normalizedCommand+ ? HETEROGENEOUS_AGENT_CONFIGS.find(+ ({ defaultCommand, type }) =>+ LEGACY_COMMAND_INFERENCE_TYPES.has(type) &&+ normalizedCommand.includes(defaultCommand.toLowerCase()),+ )?.type+ : undefined;+ const type = explicitType ?? adapterType ?? inferredType ?? 'claude-code';+ const normalizedConfig = { ...legacyConfig };+ delete normalizedConfig.adapterType;++ return { ...normalizedConfig, type };+};++const normalizeAgencyConfigHeterogeneousProvider = (+ agencyConfig: LobeAgentAgencyConfig | null | undefined,+): LobeAgentAgencyConfig | undefined => {+ const base = agencyConfig ?? undefined;+ if (!base?.heterogeneousProvider) return base;++ const heterogeneousProvider = normalizeHeterogeneousProviderConfig(base.heterogeneousProvider);+ return heterogeneousProvider === base.heterogeneousProvider+ ? base+ : { ...base, heterogeneousProvider };+};+interface ClaudeCodeSelectionSource {args?: string[];effort?: string | null;@@ -780,7 +852,7 @@ export const resolveAgencyConfig = (agencyConfig: LobeAgentAgencyConfig | null | undefined,override: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'> | null | undefined,): LobeAgentAgencyConfig | undefined => {- const base = agencyConfig ?? undefined;+ const base = normalizeAgencyConfigHeterogeneousProvider(agencyConfig);if (base?.executionTargetSelectionPolicy === 'fixed') return base;if (!override) return base;const hasTarget = override.executionTarget !== undefined;@@ -813,12 +885,12 @@ export const resolveAgentAgencyConfig = (override: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'> | null | undefined,context: AgentAgencyConfigContext,): LobeAgentAgencyConfig | undefined => {+ const base = normalizeAgencyConfigHeterogeneousProvider(agencyConfig);const isPublicWorkspaceAgent =!!context.workspaceId && context.visibility !== 'private' && context.canManage !== true;- if (isPublicWorkspaceAgent) return resolveAgencyConfig(agencyConfig, override);+ if (isPublicWorkspaceAgent) return resolveAgencyConfig(base, override);- const base = agencyConfig ?? undefined;if (!base?.executionTargetSelectionPolicy) return base;const { executionTargetSelectionPolicy, ...ownerConfig } = base;diff --git a/packages/types/src/agent/heterogeneousAgent.ts b/packages/types/src/agent/heterogeneousAgent.tsnew file mode 100644index 00000000000..c8b53adb6a9--- /dev/null+++ b/packages/types/src/agent/heterogeneousAgent.ts@@ -0,0 +1,206 @@+export interface HeterogeneousAgentAuthDescriptor {+ docsUrl: string;+ errorMessage: string;+ /** Case-insensitive RegExp sources used to recognize authentication failures. */+ patterns: readonly string[];+ signInCommand: string;+}++export interface HeterogeneousAgentInstallDescriptor {+ commands: readonly string[];+ docsUrl: string;+}++/**+ * Static, serializable source of truth for a local heterogeneous CLI agent.+ * Runtime adapters and drivers remain provider-specific; identity and host+ * metadata must be added here exactly once.+ */+export interface LocalHeterogeneousAgentDescriptor {+ auth: HeterogeneousAgentAuthDescriptor;+ defaultCommand: string;+ iconId: string;+ install: HeterogeneousAgentInstallDescriptor;+ kind: 'local-cli';+ menuKey: string;+ menuLabelKey: string;+ resume: { supported: boolean };+ title: string;+ type: string;+}++const COMMON_AUTH_REQUIRED_PATTERNS = [+ 'failed to authenticate',+ 'invalid authentication credentials',+ 'authentication[_ ]error',+ 'not authenticated',+ '\\bunauthorized\\b',+ '\\b401\\b',+ 'no api key found',+ 'no models available',+] as const;++export const HETEROGENEOUS_AGENT_CONFIGS = [+ {+ auth: {+ docsUrl: 'https://ampcode.com/manual',+ errorMessage:+ 'Amp could not authenticate. Run `amp login` or configure AMP_API_KEY, then retry.',+ patterns: [...COMMON_AUTH_REQUIRED_PATTERNS, 'please (?:log|sign) in', 'amp_api_key'],+ signInCommand: 'amp login',+ },+ defaultCommand: 'amp',+ iconId: 'Amp',+ install: {+ commands: [+ 'curl -fsSL https://ampcode.com/install.sh | bash',+ 'brew install ampcode/tap/ampcode',+ ],+ docsUrl: 'https://ampcode.com/manual',+ },+ kind: 'local-cli',+ menuKey: 'newAmpAgent',+ menuLabelKey: 'newAmpAgent',+ resume: { supported: true },+ title: 'Amp',+ type: 'amp',+ },+ {+ auth: {+ docsUrl: 'https://docs.anthropic.com/en/docs/claude-code/setup',+ errorMessage:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ patterns: COMMON_AUTH_REQUIRED_PATTERNS,+ signInCommand: 'claude',+ },+ defaultCommand: 'claude',+ iconId: 'ClaudeCode',+ install: {+ commands: [+ 'curl -fsSL https://claude.ai/install.sh | bash',+ 'brew install --cask claude-code',+ ],+ docsUrl: 'https://docs.anthropic.com/en/docs/claude-code/setup',+ },+ kind: 'local-cli',+ menuKey: 'newClaudeCodeAgent',+ menuLabelKey: 'newClaudeCodeAgent',+ resume: { supported: true },+ title: 'Claude Code',+ type: 'claude-code',+ },+ {+ auth: {+ docsUrl: 'https://github.com/openai/codex#installing-and-running-codex-cli',+ errorMessage:+ 'Codex could not authenticate. Sign in again or refresh its credentials, then retry.',+ patterns: COMMON_AUTH_REQUIRED_PATTERNS,+ signInCommand: 'codex',+ },+ defaultCommand: 'codex',+ iconId: 'Codex',+ install: {+ commands: ['npm install -g @openai/codex', 'brew install --cask codex'],+ docsUrl: 'https://github.com/openai/codex#installing-and-running-codex-cli',+ },+ kind: 'local-cli',+ menuKey: 'newCodexAgent',+ menuLabelKey: 'newCodexAgent',+ resume: { supported: true },+ title: 'Codex',+ type: 'codex',+ },+ {+ auth: {+ docsUrl: 'https://opencode.ai/docs',+ errorMessage:+ 'OpenCode could not authenticate. Sign in again or refresh its credentials, then retry.',+ patterns: [+ ...COMMON_AUTH_REQUIRED_PATTERNS,+ 'authentication',+ 'invalid.*(?:credential|token|key)',+ ],+ signInCommand: 'opencode auth login',+ },+ defaultCommand: 'opencode',+ iconId: 'OpenCode',+ install: {+ commands: ['curl -fsSL https://opencode.ai/install | bash'],+ docsUrl: 'https://opencode.ai/docs',+ },+ kind: 'local-cli',+ menuKey: 'newOpenCodeAgent',+ menuLabelKey: 'newOpenCodeAgent',+ resume: { supported: true },+ title: 'OpenCode',+ type: 'opencode',+ },+ {+ auth: {+ docsUrl: 'https://github.com/earendil-works/pi',+ errorMessage: 'Pi could not authenticate. Run `pi`, use `/login`, then retry.',+ patterns: [+ ...COMMON_AUTH_REQUIRED_PATTERNS,+ 'invalid (?:authentication )?(?:credentials?|tokens?|api keys?)',+ ],+ signInCommand: 'pi',+ },+ defaultCommand: 'pi',+ iconId: 'Pi',+ install: {+ commands: ['npm install -g @earendil-works/pi-coding-agent'],+ docsUrl: 'https://github.com/earendil-works/pi',+ },+ kind: 'local-cli',+ menuKey: 'newPiAgent',+ menuLabelKey: 'newPiAgent',+ resume: { supported: true },+ title: 'Pi',+ type: 'pi',+ },+ {+ auth: {+ docsUrl: 'https://docs.qoder.com/cli/auth.md',+ errorMessage: 'Qoder could not authenticate. Run `qodercli login`, then retry.',+ patterns: [...COMMON_AUTH_REQUIRED_PATTERNS, 'not logged in', 'please run \\/login'],+ signInCommand: 'qodercli login',+ },+ defaultCommand: 'qodercli',+ iconId: 'Qoder',+ install: {+ commands: [+ 'curl -fsSL https://qoder.com/install | bash',+ 'npm install -g @qoder-ai/qodercli',+ ],+ docsUrl: 'https://docs.qoder.com/cli/install.md',+ },+ kind: 'local-cli',+ menuKey: 'newQoderAgent',+ menuLabelKey: 'newQoderAgent',+ resume: { supported: true },+ title: 'Qoder',+ type: 'qoder',+ },+] as const satisfies readonly LocalHeterogeneousAgentDescriptor[];++export interface RemoteHeterogeneousAgentDescriptor {+ kind: 'remote-task';+ title: string;+ type: string;+}++export const REMOTE_HETEROGENEOUS_AGENT_CONFIGS = [+ { kind: 'remote-task', title: 'OpenClaw', type: 'openclaw' },+ { kind: 'remote-task', title: 'Hermes', type: 'hermes' },+] as const satisfies readonly RemoteHeterogeneousAgentDescriptor[];++export type HeterogeneousAgentDescriptor =+ | (typeof HETEROGENEOUS_AGENT_CONFIGS)[number]+ | (typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number];++export type HeterogeneousAgentMenuLabelKey =+ (typeof HETEROGENEOUS_AGENT_CONFIGS)[number]['menuLabelKey'];+export type LocalHeterogeneousAgentType = (typeof HETEROGENEOUS_AGENT_CONFIGS)[number]['type'];+export type RemoteHeterogeneousAgentType =+ (typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number]['type'];+export type HeterogeneousAgentType = LocalHeterogeneousAgentType | RemoteHeterogeneousAgentType;diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.tsindex 2d242ee3245..a08753b8178 100644--- a/packages/types/src/agent/index.ts+++ b/packages/types/src/agent/index.ts@@ -4,6 +4,7 @@ export * from './chatConfig';export * from './displayName';export * from './document';export * from './graph';+export * from './heterogeneousAgent';export * from './item';export * from './modelSelection';export * from './pluginConfig';diff --git a/src/features/ConnectAgent/providers.ts b/src/features/ConnectAgent/providers.tsindex 5bd5e20b14e..240a937c56b 100644--- a/src/features/ConnectAgent/providers.ts+++ b/src/features/ConnectAgent/providers.ts@@ -50,7 +50,7 @@ export const CONNECTABLE_PROVIDERS: ConnectableProvider[] = [...HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map((config) => ({avatar: config.avatar,brand: CLI_BRANDS[config.type],- command: config.command,+ command: config.defaultCommand,kind: 'cli' as const,title: config.title,type: config.type,diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsxindex 195300b3fa5..cf563fce584 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx@@ -1,17 +1,5 @@-import {- AMP_CLI_INSTALL_COMMANDS,- AMP_CLI_INSTALL_DOCS_URL,- CLAUDE_CODE_CLI_INSTALL_COMMANDS,- CLAUDE_CODE_CLI_INSTALL_DOCS_URL,- CODEX_CLI_INSTALL_COMMANDS,- CODEX_CLI_INSTALL_DOCS_URL,- OPENCODE_CLI_INSTALL_COMMANDS,- OPENCODE_CLI_INSTALL_DOCS_URL,- PI_CLI_INSTALL_COMMANDS,- PI_CLI_INSTALL_DOCS_URL,- QODER_CLI_INSTALL_COMMANDS,- QODER_CLI_INSTALL_DOCS_URL,-} from '@lobechat/electron-client-ipc';+import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import { HETEROGENEOUS_AGENT_CONFIGS } from '@lobechat/heterogeneous-agents';import { Amp, ClaudeCode, Codex, OpenCode, Pi, Qoder } from '@lobehub/icons';import {@@ -20,56 +8,53 @@ import {type SupportedHeterogeneousAgentType,} from './types';-export const HETEROGENEOUS_AGENT_GUIDE_CONFIG = {+const GUIDE_PRESENTATION_CONFIG = {'amp': {- docsUrl: AMP_CLI_INSTALL_DOCS_URL,icon: Amp,- installCommands: AMP_CLI_INSTALL_COMMANDS,- signInCommand: 'amp login',- title: 'Amp',translationPrefix: 'ampInstallGuide',},'claude-code': {- docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,icon: ClaudeCode,- installCommands: CLAUDE_CODE_CLI_INSTALL_COMMANDS,- signInCommand: 'claude',- title: 'Claude Code',translationPrefix: 'claudeCodeInstallGuide',},'codex': {- docsUrl: CODEX_CLI_INSTALL_DOCS_URL,icon: Codex,- installCommands: CODEX_CLI_INSTALL_COMMANDS,- signInCommand: 'codex',- title: 'Codex',translationPrefix: 'codexInstallGuide',},'opencode': {- docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,icon: OpenCode,- installCommands: OPENCODE_CLI_INSTALL_COMMANDS,- signInCommand: 'opencode auth login',- title: 'OpenCode',translationPrefix: 'opencodeInstallGuide',},'pi': {- docsUrl: PI_CLI_INSTALL_DOCS_URL,icon: Pi,- installCommands: PI_CLI_INSTALL_COMMANDS,- signInCommand: 'pi',- title: 'Pi',translationPrefix: 'piInstallGuide',},'qoder': {- docsUrl: QODER_CLI_INSTALL_DOCS_URL,icon: Qoder,- installCommands: QODER_CLI_INSTALL_COMMANDS,- signInCommand: 'qodercli login',- title: 'Qoder',translationPrefix: 'qoderInstallGuide',},-} as const satisfies Record<SupportedHeterogeneousAgentType, HeterogeneousAgentGuideConfig>;+} as const satisfies Record<+ LocalHeterogeneousAgentType,+ Pick<HeterogeneousAgentGuideConfig, 'icon' | 'translationPrefix'>+>;++const createGuideConfig = () => {+ const configs = {} as Record<SupportedHeterogeneousAgentType, HeterogeneousAgentGuideConfig>;++ for (const descriptor of HETEROGENEOUS_AGENT_CONFIGS) {+ configs[descriptor.type] = {+ docsUrl: descriptor.install.docsUrl,+ installCommands: descriptor.install.commands,+ signInCommand: descriptor.auth.signInCommand,+ title: descriptor.title,+ ...GUIDE_PRESENTATION_CONFIG[descriptor.type],+ };+ }++ return configs;+};++export const HETEROGENEOUS_AGENT_GUIDE_CONFIG = createGuideConfig();export const isSupportedHeterogeneousAgentType = (value?: string,diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.tsindex 152220e3634..4a28834c0ff 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts@@ -1,4 +1,6 @@import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';+import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import { LOCAL_HETEROGENEOUS_AGENT_TYPES } from '@lobechat/heterogeneous-agents';import type { ComponentType } from 'react';export type HeterogeneousAgentStatusGuideVariant = 'compact' | 'embedded' | 'inline';@@ -41,16 +43,9 @@ export interface HeterogeneousAgentStatusGuideProps {variant?: HeterogeneousAgentStatusGuideVariant;}-export const SUPPORTED_HETEROGENEOUS_AGENT_TYPES = [- 'amp',- 'claude-code',- 'codex',- 'opencode',- 'pi',- 'qoder',-] as const;+export const SUPPORTED_HETEROGENEOUS_AGENT_TYPES = LOCAL_HETEROGENEOUS_AGENT_TYPES;-export type SupportedHeterogeneousAgentType = (typeof SUPPORTED_HETEROGENEOUS_AGENT_TYPES)[number];+export type SupportedHeterogeneousAgentType = LocalHeterogeneousAgentType;export interface HeterogeneousAgentGuideConfig {docsUrl: string;diff --git a/src/features/Recommendations/hooks/useHeteroDetections.ts b/src/features/Recommendations/hooks/useHeteroDetections.tsindex 5a46c68e83c..2db22faeceb 100644--- a/src/features/Recommendations/hooks/useHeteroDetections.ts+++ b/src/features/Recommendations/hooks/useHeteroDetections.ts@@ -24,7 +24,7 @@ export const useHeteroDetections = (): HeteroDetectionMap => {try {const status = await binaryService.detectHeterogeneousAgentCommand({agentType: config.type,- command: config.command,+ command: config.defaultCommand,});return [config.type, status] as const;} catch (error) {diff --git a/src/hooks/useCreateHeteroAgent.ts b/src/hooks/useCreateHeteroAgent.tsindex 6a27dacad29..bb9d8800f37 100644--- a/src/hooks/useCreateHeteroAgent.ts+++ b/src/hooks/useCreateHeteroAgent.ts@@ -31,7 +31,7 @@ export const useCreateHeteroAgent = () => {config: {agencyConfig: {heterogeneousProvider: {- command: definition.command,+ command: definition.defaultCommand,type: definition.type,},},diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsxindex c4b5aacd09b..537c2f0f4eb 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx@@ -19,24 +19,24 @@ vi.mock('@lobechat/heterogeneous-agents/client', () => ({getHeterogeneousAgentClientConfig: (type: string) =>type === 'claude-code'? {- command: 'claude',+ defaultCommand: 'claude',icon: () => <span>Claude Code Icon</span>,title: 'Claude Code',}: type === 'opencode'? {- command: 'opencode',+ defaultCommand: 'opencode',icon: () => <span>OpenCode Icon</span>,title: 'OpenCode',}: type === 'pi'? {- command: 'pi',+ defaultCommand: 'pi',icon: () => <span>Pi Icon</span>,title: 'Pi',}: {- command: 'codex',+ defaultCommand: 'codex',icon: () => <span>Codex Icon</span>,title: 'Codex',},diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsxindex 1169e086e03..b50132a53b6 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx@@ -219,7 +219,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(const navigate = useWorkspaceAwareNavigate();const { allowed: canEdit } = usePermission('edit_own_content');const providerConfig = getHeterogeneousAgentClientConfig(provider.type);- const defaultCommand = providerConfig?.command || '';+ const defaultCommand = providerConfig?.defaultCommand || '';const resolvedCommand = provider.command?.trim() || defaultCommand;const isUsingCustomCommand = resolvedCommand !== defaultCommand;const [status, setStatus] = useState<BinaryStatus | undefined>();diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex b295626b2ca..c839e0c82cb 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -17,7 +17,7 @@ import type * as LobeChatConst from '@lobechat/const';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import type { AgentEventAdapter } from '@lobechat/heterogeneous-agents';import { createAdapter } from '@lobechat/heterogeneous-agents';-import type { ChatTopicMetadata } from '@lobechat/types';+import type { ChatTopicMetadata, HeterogeneousProviderConfig } from '@lobechat/types';import { ThreadStatus } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -1796,6 +1796,26 @@ describe('heterogeneousAgentExecutor DB persistence', () => {);});+ it('should execute a persisted legacy provider config without type', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);+ const legacyProvider = {+ command: '/usr/local/bin/custom-codex',+ } as unknown as HeterogeneousProviderConfig;++ await executeHeterogeneousAgent(get, {+ ...defaultParams,+ heterogeneousProvider: legacyProvider,+ });++ expect(mockStartSession).toHaveBeenCalledWith(+ expect.objectContaining({+ agentType: 'codex',+ command: '/usr/local/bin/custom-codex',+ }),+ );+ });+it('should pass the Codex app-server lab preference to the desktop session', async () => {const store = createMockStore();const get = vi.fn(() => store);diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex d10d1ae484e..1fedf89d1c3 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -3,23 +3,19 @@ import type {AgentInterventionResponseData,AgentStreamEvent,} from '@lobechat/agent-gateway-client';+import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import {- AMP_CLI_INSTALL_DOCS_URL,- CLAUDE_CODE_CLI_INSTALL_DOCS_URL,- CODEX_CLI_INSTALL_DOCS_URL,- type HeterogeneousAgentSessionError,- HeterogeneousAgentSessionErrorCode,- OPENCODE_CLI_INSTALL_DOCS_URL,- PI_CLI_INSTALL_DOCS_URL,- QODER_CLI_AUTH_DOCS_URL,-} from '@lobechat/electron-client-ipc';-import {+ buildHeterogeneousAgentAuthRequiredError,createMainAgentRunState,+ isHeterogeneousAgentAuthRequired,+ isLocalHeterogeneousType,type MainAgentIntent,type MainAgentReduceCtx,type MainAgentRunState,reduceMainAgent,rehydrateSubagentRunsState,+ resolveHeterogeneousAgentCommand,type SubagentIntent,type SubagentRunSnapshot,} from '@lobechat/heterogeneous-agents';@@ -41,6 +37,7 @@ import type {import {AgentRuntimeErrorType,buildHeteroSpawnArgs,+ normalizeHeterogeneousProviderConfig,ThreadStatus,ThreadType,} from '@lobechat/types';@@ -89,101 +86,13 @@ const markSkipMessageFetch = (event: AgentStreamEvent): void => {event.data = { ...event.data, skipMessageFetch: true };};-const CLI_AUTH_REQUIRED_PATTERNS = [- /failed to authenticate/i,- /invalid authentication credentials/i,- /authentication[_ ]error/i,- /not authenticated/i,- /\bunauthorized\b/i,- /\b401\b/,- /no api key found/i,- /no models available/i,-] as const;-const AMP_AUTH_REQUIRED_PATTERNS = [/please (?:log|sign) in/i, /amp_api_key/i] as const;-const QODER_AUTH_REQUIRED_PATTERNS = [/not logged in/i, /please run \/login/i] as const;--const buildCliAuthRequiredSessionError = (- agentType: 'amp' | 'claude-code' | 'codex' | 'opencode' | 'pi' | 'qoder',- rawMessage: string,-): HeterogeneousAgentSessionError => {- switch (agentType) {- case 'amp': {- return {- agentType,- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- docsUrl: AMP_CLI_INSTALL_DOCS_URL,- message:- 'Amp could not authenticate. Run `amp login` or configure AMP_API_KEY, then retry.',- stderr: rawMessage,- };- }- case 'claude-code': {- return {- agentType,- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,- message:- 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',- stderr: rawMessage,- };- }- case 'codex': {- return {- agentType,- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- docsUrl: CODEX_CLI_INSTALL_DOCS_URL,- message:- 'Codex could not authenticate. Sign in again or refresh its credentials, then retry.',- stderr: rawMessage,- };- }- case 'opencode': {- return {- agentType,- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,- message:- 'OpenCode could not authenticate. Sign in again or refresh its credentials, then retry.',- stderr: rawMessage,- };- }- case 'pi': {- return {- agentType,- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- docsUrl: PI_CLI_INSTALL_DOCS_URL,- message: 'Pi could not authenticate. Run `pi`, use `/login`, then retry.',- stderr: rawMessage,- };- }- case 'qoder': {- return {- agentType,- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- docsUrl: QODER_CLI_AUTH_DOCS_URL,- message: 'Qoder could not authenticate. Run `qodercli login`, then retry.',- stderr: rawMessage,- };- }- }-};-const normalizeErrorText = (value?: string) => value?.replaceAll(/\s+/g, ' ').trim();const maybeClassifyCliAuthRequiredError = (error: unknown,agentType?: string,): HeterogeneousAgentSessionError | undefined => {- if (- agentType !== 'amp' &&- agentType !== 'claude-code' &&- agentType !== 'codex' &&- agentType !== 'opencode' &&- agentType !== 'pi' &&- agentType !== 'qoder'- ) {- return;- }+ if (!agentType || !isLocalHeterogeneousType(agentType)) return;const message =error instanceof Error@@ -198,15 +107,9 @@ const maybeClassifyCliAuthRequiredError = (: undefined;if (!message) return;- const patterns =- agentType === 'amp'- ? [...CLI_AUTH_REQUIRED_PATTERNS, ...AMP_AUTH_REQUIRED_PATTERNS]- : agentType === 'qoder'- ? [...CLI_AUTH_REQUIRED_PATTERNS, ...QODER_AUTH_REQUIRED_PATTERNS]- : CLI_AUTH_REQUIRED_PATTERNS;- if (!patterns.some((pattern) => pattern.test(message))) return;-- return buildCliAuthRequiredSessionError(agentType, message);+ if (!isHeterogeneousAgentAuthRequired(agentType, message)) return;++ return buildHeterogeneousAgentAuthRequiredError({ agentType, stderr: message });};const shouldSuppressTerminalErrorEcho = (content: string, error: ChatMessageError): boolean => {@@ -227,29 +130,6 @@ const shouldSuppressTerminalErrorEcho = (content: string, error: ChatMessageErroreturn !!normalizedContent && !!normalizedRawError && normalizedContent === normalizedRawError;};-const getDefaultHeterogeneousCommand = (agentType: string): string => {- switch (agentType) {- case 'amp': {- return 'amp';- }- case 'codex': {- return 'codex';- }- case 'opencode': {- return 'opencode';- }- case 'pi': {- return 'pi';- }- case 'qoder': {- return 'qodercli';- }- default: {- return 'claude';- }- }-};-const toHeterogeneousAgentMessageError = (error: unknown, agentType?: string): ChatMessageError => {const authRequiredError = maybeClassifyCliAuthRequiredError(error, agentType);if (authRequiredError) {@@ -389,23 +269,6 @@ const getTopicMetadataById = (}};-/**- * Map heterogeneousProvider.command to adapter type key.- */-const resolveAdapterType = (config: HeterogeneousProviderConfig): string => {- if (config.type) return config.type;- // Explicit adapterType in config takes priority- if ((config as any).adapterType) return (config as any).adapterType;-- // Infer from command name- const cmd = config.command || 'claude';- if (cmd.includes('claude')) return 'claude-code';- if (cmd.includes('codex')) return 'codex';- if (cmd.includes('kimi')) return 'kimi-cli';-- return 'claude-code'; // default-};-const asRecord = (value: unknown): Record<string, unknown> =>value && typeof value === 'object' ? (value as Record<string, unknown>) : {};@@ -596,7 +459,7 @@ export const executeHeterogeneousAgent = async (params: HeterogeneousAgentExecutorParams,): Promise<void> => {const {- heterogeneousProvider,+ heterogeneousProvider: persistedHeterogeneousProvider,contextSelections,assistantMessageId,context,@@ -609,7 +472,10 @@ export const executeHeterogeneousAgent = async (workingDirectoryConfig,} = params;- const adapterType = resolveAdapterType(heterogeneousProvider);+ const heterogeneousProvider = normalizeHeterogeneousProviderConfig(+ persistedHeterogeneousProvider,+ );+ const adapterType = heterogeneousProvider.type;// Which real provider account this run consumes, resolved once after spawn// from the FINAL env (so an agent-env override is attributed correctly, not@@ -1961,7 +1827,7 @@ export const executeHeterogeneousAgent = async (const result = await heterogeneousAgentService.startSession({agentType: adapterType,args: buildHeteroSpawnArgs(heterogeneousProvider),- command: heterogeneousProvider.command || getDefaultHeterogeneousCommand(adapterType),+ command: resolveHeterogeneousAgentCommand(adapterType, heterogeneousProvider.command),cwd: workingDirectory,env: sessionEnv,resumeSessionId,