π€― 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
π fix(heterogeneous-agent): detect official TRAE CLI (#18426)
AmAzing-9d1f47d5e615
diff --git a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.tsindex 69b9e2b4cb0..73487244e3f 100644--- a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts+++ b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts@@ -50,6 +50,9 @@ const npmShim = (packagePath: string) =>`@ECHO off\r\n"%dp0%\\node.exe" "%dp0%\\${packagePath}" %*\r\n`;const noErr = null;+const TRAE_ACP_HELP = `Start the ACP server+Usage: trae-cli acp serve [flags]+ -y, --yolo Enable YOLO mode`;const callExecFile = (stdout: string, stderr = '') => {execFileMock.mockImplementationOnce(((file: string, args: any, opts: any, cb: any) => {// promisify-wrapped: the callback is always the last positional arg.@@ -324,20 +327,17 @@ describe('cliAgentBinaries', () => {});});- it('detects TRAE Enterprise and rejects the unrelated trae-cli binary', async () => {+ it('detects the official TRAE CLI by its ACP capability', async () => {callExecFile('/Users/test/.local/bin/traecli\n');- callExecFile('TraeCode CLI 1.4.0');+ callExecFile('trae-cli version 0.120.52');+ callExecFile(TRAE_ACP_HELP);const { traeBinary } = await import('../cliAgentBinaries');await expect(traeBinary.detect()).resolves.toMatchObject({available: true,path: '/Users/test/.local/bin/traecli',- version: '1.4.0',+ version: '0.120.52',});-- callExecFile('/Users/test/.local/bin/traecli\n');- callExecFile('trae-cli 0.1.0');- await expect(traeBinary.detect()).resolves.toEqual({ available: false });});it('runs the binary directly via execFile (no shell)', async () => {diff --git a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.tsindex 7135618ea20..9ae27756816 100644--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts@@ -142,7 +142,7 @@ export const qoderBinary: BinarySpec = {priority: 6,};-/** TRAE Enterprise CLI (TraeCode CLI), not the unrelated open-source `trae-cli`. */+/** TRAE Enterprise CLI, capability-checked against its ACP runtime. */export const traeBinary: BinarySpec = {description: 'TRAE CLI - ByteDance enterprise agentic coding CLI',detect: () => detectHeterogeneousCliCommand('trae', 'traecli'),diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.tsindex cf3e3854910..86c83ab0178 100644--- a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.ts@@ -61,7 +61,7 @@ const assertWindowsCommandLineFits = ({ args, command }: CliSpawnPlan): void =>);};-const isPathLikeCommand = (command: string) =>+export const isPathLikeCommand = (command: string) =>path.win32.isAbsolute(command) || path.posix.isAbsolute(command) || /[\\/]/.test(command);const fileExists = async (filePath: string): Promise<boolean> => {diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.tsindex 19d3d520511..2ed7a19712a 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts@@ -50,6 +50,13 @@ const existingFiles = (files: Record<string, string | true>) => {};const noErr = null;+const TRAE_ACP_HELP = `Start the ACP server++Usage:+ trae-cli acp serve [flags]++Flags:+ -y, --yolo Enable YOLO mode`;const callExecFile = (stdout: string, stderr = '') => {execFileMock.mockImplementationOnce(((file: string, args: any, opts: any, cb: any) => {// promisify-wrapped: the callback is always the last positional arg.@@ -284,9 +291,12 @@ describe('resolveCliCommand', () => {}});- it('resolves and validates the TRAE Enterprise CLI', async () => {+ it('accepts the official TRAE banner when the CLI exposes the ACP runtime', async () => {callExecFile('/usr/local/bin/traecli\n');- callExecFile('TraeCode CLI 1.4.0');+ callExecFile(`trae-cli version 0.120.52+build date: 2026-08-12T01:31:30Z+build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);+ callExecFile(TRAE_ACP_HELP);const { detectHeterogeneousCliCommand } = await importModule();const status = await detectHeterogeneousCliCommand('trae', 'traecli');@@ -294,13 +304,15 @@ describe('resolveCliCommand', () => {expect(status).toMatchObject({available: true,path: '/usr/local/bin/traecli',- version: '1.4.0',+ version: '0.120.52',});+ expect(execFileMock.mock.calls[2]![1]).toEqual(['acp', 'serve', '--help']);});it('accepts the TRAE Enterprise CLI bare-semver banner', async () => {callExecFile('/usr/local/bin/traecli\n');callExecFile('1.4.0');+ callExecFile(TRAE_ACP_HELP);const { detectHeterogeneousCliCommand } = await importModule();@@ -311,22 +323,38 @@ describe('resolveCliCommand', () => {});});- it('rejects the unrelated open-source trae-cli trajectory runner', async () => {+ it('accepts the official canonical trae-cli executable when it exposes ACP', async () => {+ callExecFile('trae-cli version 0.120.52');+ callExecFile(TRAE_ACP_HELP);+ const probeEnv = { ...process.env, PATH: '/custom/node/bin:/usr/bin' };+const { detectHeterogeneousCliCommand } = await importModule();- const status = await detectHeterogeneousCliCommand('trae', '/usr/local/bin/trae-cli');+ const status = await detectHeterogeneousCliCommand(+ 'trae',+ '/usr/local/bin/trae-cli',+ probeEnv,+ );- expect(status.available).toBe(false);- expect(execFileMock).not.toHaveBeenCalled();+ expect(status).toMatchObject({+ available: true,+ path: '/usr/local/bin/trae-cli',+ resolvedPathEnv: '/custom/node/bin:/usr/bin',+ version: '0.120.52',+ });+ expect(execFileMock.mock.calls[0]![2]).toMatchObject({ env: probeEnv });+ expect(execFileMock.mock.calls[1]![2]).toMatchObject({ env: probeEnv });});- it('rejects the unrelated trae-cli banner even when the executable was renamed', async () => {+ it('rejects the unrelated trae-cli trajectory runner by its missing ACP capability', async () => {callExecFile('/usr/local/bin/traecli\n');callExecFile('trae-cli 0.1.0');+ callExecFileError(new Error('unknown command "acp"'));const { detectHeterogeneousCliCommand } = await importModule();- const status = await detectHeterogeneousCliCommand('trae', 'traecli');+ const status = await detectHeterogeneousCliCommand('trae', 'traecli-renamed');expect(status).toEqual({ available: false });+ expect(execFileMock.mock.calls[2]![1]).toEqual(['acp', 'serve', '--help']);});it('finds OpenCode in its well-known user-local install path', async () => {@@ -727,6 +755,37 @@ describe('resolveCliCommand', () => {}});+ it('finds TRAE in its official Windows install directory when PATH is missing it', async () => {+ const originalLocalAppData = process.env.LOCALAPPDATA;+ const originalPath = process.env.PATH;+ const localAppData = 'C:\\Users\\x\\AppData\\Local';+ const traeCli = `${localAppData}\\trae-cli\\bin\\traecli.exe`;+ process.env.LOCALAPPDATA = localAppData;+ process.env.PATH = 'C:\\Windows';++ try {+ existingFiles({ [traeCli]: true });+ callExecFileError(new Error('not found')); // where traecli+ callExecFileError(new Error('no registry')); // reg query HKLM+ callExecFileError(new Error('no registry')); // reg query HKCU+ callExecFile('trae-cli version 0.120.52');+ callExecFile(TRAE_ACP_HELP);++ const { detectHeterogeneousCliCommand } = await importModule();+ const status = await detectHeterogeneousCliCommand('trae', 'traecli');++ expect(status).toMatchObject({+ available: true,+ path: traeCli,+ version: '0.120.52',+ });+ } finally {+ process.env.PATH = originalPath;+ if (originalLocalAppData === undefined) delete process.env.LOCALAPPDATA;+ else process.env.LOCALAPPDATA = originalLocalAppData;+ }+ });+it('capability-probes a Kimi .cmd shim without constructing a shell command', async () => {const commandPath = 'C:\\Users\\x\\AppData\\Roaming\\npm\\kimi.cmd';const scriptPath = 'C:\\Users\\x\\AppData\\Roaming\\npm\\node_modules\\kimi-code\\cli.js';diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex 1d84ae0556f..d8ca6268b28 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -45,7 +45,6 @@ export interface CliCommandStatus {}interface ValidateOptions {- rejectPattern?: RegExp;validateFlag?: string;/** Capability-probe argv. Defaults to `--help`. */validateHelpArgs?: string[];@@ -59,6 +58,7 @@ interface ValidateOptions {interface ResolvedCommand {env?: NodeJS.ProcessEnv;path: string;+ resolvedPathEnv?: string;}const VERSION_PATTERN = /v?(\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?)/;@@ -252,17 +252,27 @@ const getCommandPathLines = async (* makes detection immune to unknown shim shapes instead of chasing them with* more regexes.*/-const resolveCommandCandidates = async (command: string): Promise<ResolvedCommand[]> => {+const resolveCommandCandidates = async (+ command: string,+ probeEnv?: NodeJS.ProcessEnv,+): Promise<ResolvedCommand[]> => {const trimmedCommand = command.trim();if (!trimmedCommand) return [];if (isPathLikeCommand(trimmedCommand)) {- return [{ path: trimmedCommand }];+ return [+ {+ env: probeEnv,+ path: trimmedCommand,+ resolvedPathEnv: probeEnv?.PATH === process.env.PATH ? undefined : probeEnv?.PATH,+ },+ ];}const whichCommand = isWindows() ? 'where' : 'which';- let lines = await getCommandPathLines(whichCommand, trimmedCommand);- let lookupEnv: NodeJS.ProcessEnv | undefined;+ let lines = await getCommandPathLines(whichCommand, trimmedCommand, probeEnv);+ let lookupEnv = probeEnv;+ let resolvedPathEnv = probeEnv?.PATH === process.env.PATH ? undefined : probeEnv?.PATH;if (!lines) {// PATH recovery, per platform: macOS/Linux re-read the login shell's PATH,@@ -271,15 +281,18 @@ const resolveCommandCandidates = async (command: string): Promise<ResolvedCommanconst recoveredPath = isWindows()? await getWindowsRegistryPath(): await getCachedLoginShellPath();- const lookupPath = mergePathValues(recoveredPath, process.env.PATH);+ const lookupPath = mergePathValues(recoveredPath, probeEnv?.PATH ?? process.env.PATH);- if (lookupPath && lookupPath !== process.env.PATH) {+ if (lookupPath && lookupPath !== (probeEnv?.PATH ?? process.env.PATH)) {const fallbackEnv = {- ...process.env,+ ...(probeEnv ?? process.env),PATH: lookupPath,};lines = await getCommandPathLines(whichCommand, trimmedCommand, fallbackEnv);- if (lines) lookupEnv = fallbackEnv;+ if (lines) {+ lookupEnv = fallbackEnv;+ resolvedPathEnv = lookupPath;+ }}}@@ -292,10 +305,11 @@ const resolveCommandCandidates = async (command: string): Promise<ResolvedCommanreturn pickWindowsRunnables(lines).map((runnablePath) => ({env: lookupEnv,path: runnablePath,+ resolvedPathEnv,}));}- return [{ env: lookupEnv, path: lines[0] }];+ return [{ env: lookupEnv, path: lines[0], resolvedPathEnv }];};const quoteWindowsShellToken = (token: string): string =>@@ -381,13 +395,13 @@ const execProbe = async (export const detectValidatedCommand = async (command: string,options: ValidateOptions,+ probeEnv?: NodeJS.ProcessEnv,): Promise<CliCommandStatus> => {const trimmedCommand = command.trim();if (!trimmedCommand) return { available: false };if (isWindows() && WINDOWS_SHELL_METAS.test(trimmedCommand)) return { available: false };const {- rejectPattern,validateFlag = '--version',validateHelpArgs = ['--help'],validateHelpKeywords,@@ -399,11 +413,11 @@ export const detectValidatedCommand = async (// Resolve via where/which BEFORE invoking. On Windows this is what discovers// npm-installed shims like `claude.cmd` under %APPDATA%\npm β `execFile`// alone won't apply PATHEXT and can't run .cmd files directly.- const candidates = await resolveCommandCandidates(trimmedCommand);+ const candidates = await resolveCommandCandidates(trimmedCommand, probeEnv);if (candidates.length === 0) return { available: false };const validateCandidate = async (- { env, path: resolvedPath }: ResolvedCommand,+ { env, path: resolvedPath, resolvedPathEnv }: ResolvedCommand,viaShell: boolean,): Promise<CliCommandStatus | typeof UNRESOLVED_SHIM> => {let result;@@ -417,9 +431,6 @@ export const detectValidatedCommand = async (const output = `${result.stdout}\n${result.stderr}`.trim();const firstLine = output.split(/\r?\n/)[0]!.trim();const loweredOutput = output.toLowerCase();- if (rejectPattern?.test(firstLine) || rejectPattern?.test(output)) {- return { available: false };- }const matchesKeyword = validateKeywords?.some((keyword) =>loweredOutput.includes(keyword.toLowerCase()),);@@ -434,9 +445,9 @@ export const detectValidatedCommand = async (return { available: false };}- // Kimi Code shares the `kimi` executable name with the retired Python- // kimi-cli. Both can print a valid version, so capability-probe the exact- // resolved binary before accepting it as the stream-json runtime.+ // Some command names and version banners identify multiple products. When+ // configured, capability-probe the exact resolved binary before accepting+ // it as the runtime this adapter needs.if (validateHelpKeywords?.length) {let helpResult;try {@@ -473,12 +484,11 @@ export const detectValidatedCommand = async (return {available: true,path: resolvedPath,- // `env` is set only when resolution fell back to a recovered PATH (login- // shell on macOS/Linux, registry on Windows). Surface that PATH so the- // spawn site can carry it into the child env β otherwise a- // `#!/usr/bin/env node` shim resolved here can't find `node` under the- // leaner inherited PATH (Finder-launched Electron).- resolvedPathEnv: env?.PATH,+ // Surface a caller-supplied or recovered PATH when it differs from the+ // detector process, so the spawn site can preserve the environment that+ // made validation succeed. Otherwise an `#!/usr/bin/env node` shim can+ // validate here but fail when launched from a leaner host environment.+ resolvedPathEnv,// CLIs format their banners differently (`codex-cli 0.147.0`,// `1.2.3 (Claude Code)`, etc.). Keep validation against the original// output, but expose only the version so every consumer renders the same@@ -555,10 +565,11 @@ const HETEROGENEOUS_CLI_AGENT_OPTIONS = {validatePattern: /^v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/,},'trae': {- // TRAE Enterprise releases may print either a product-prefixed version or- // a bare semver. Reject the unrelated open-source trajectory runner even- // when its executable has been renamed.- rejectPattern: /^trae-cli\b/i,+ // The official binary and the unrelated open-source trajectory runner both+ // identify themselves as `trae-cli`. Distinguish them by the ACP runtime+ // LobeHub actually needs rather than by executable name or version banner.+ validateHelpArgs: ['acp', 'serve', '--help'],+ validateHelpKeywords: ['Start the ACP server', '--yolo'],validateKeywords: ['trae', 'traecode'],validatePattern: /^v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/,},@@ -698,9 +709,19 @@ const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[];}case 'trae': {- // TRAE CLI is distributed through TRAE Enterprise and has no verified- // cross-platform standalone install location. Resolve it from PATH only.- return [];+ if (platform() === 'win32') {+ const localAppData = process.env.LOCALAPPDATA;+ if (!localAppData) return [];++ const binDir = path.win32.join(localAppData, 'trae-cli', 'bin');+ return [path.win32.join(binDir, 'traecli.exe'), path.win32.join(binDir, 'trae-cli.exe')];+ }+ if (platform() !== 'darwin' && platform() !== 'linux') return [];++ return [+ path.join(homedir(), '.local', 'bin', 'traecli'),+ path.join(homedir(), '.local', 'bin', 'trae-cli'),+ ];}default: {return [];@@ -711,22 +732,12 @@ const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[export const detectHeterogeneousCliCommand = async (agentType: HeterogeneousCliAgentType,command: string,+ probeEnv?: NodeJS.ProcessEnv,): Promise<CliCommandStatus> => {- const commandName = command- .trim()- .split(/[\\/]/)- .at(-1)- ?.replace(/\.(?:bat|cmd|exe)$/i, '');- // `trae-cli` belongs to the unrelated open-source trajectory runner. LobeHub- // integrates only the TRAE Enterprise `traecli acp serve` runtime.- if (agentType === 'trae' && commandName?.toLowerCase() === 'trae-cli') {- return { available: false };- }-const validator = HETEROGENEOUS_CLI_AGENT_OPTIONS[agentType];if (!validator) return { available: false };- const status = await detectValidatedCommand(command, validator);+ const status = await detectValidatedCommand(command, validator, probeEnv);if (status.available) return status;// The default command missing from PATH may still live at a well-known install@@ -736,7 +747,7 @@ export const detectHeterogeneousCliCommand = async (// stock `claude` instead of reporting the configured command as missing.if (command.trim() === DEFAULT_HETERO_COMMAND[agentType]) {for (const candidate of getWellKnownCommandPaths(agentType)) {- const fallbackStatus = await detectValidatedCommand(candidate, validator);+ const fallbackStatus = await detectValidatedCommand(candidate, validator, probeEnv);if (fallbackStatus.available) return fallbackStatus;}}diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.tsindex 407e4f978f8..58cb22525e7 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts@@ -7,12 +7,17 @@ import { PassThrough } from 'node:stream';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as resolveCliCommand from './resolveCliCommand';+const spawnCalls: Array<{ args: string[]; command: string; options: any }> = [];let nextFakeProc: any = null;const tempDirs: string[] = [];const platformMock = vi.mocked(os.platform);const execFileMock = vi.mocked(childProcess.execFile);+const detectHeterogeneousCliCommandMock = vi.mocked(+ resolveCliCommand.detectHeterogeneousCliCommand,+);const callExecFile = (stdout: string) => {execFileMock.mockImplementationOnce(((...args: unknown[]) => {@@ -40,6 +45,11 @@ vi.mock('node:os', async () => {return { ...actual, platform: vi.fn(() => 'linux') };});+vi.mock('./resolveCliCommand', async () => {+ const actual = await vi.importActual<typeof resolveCliCommand>('./resolveCliCommand');+ return { ...actual, detectHeterogeneousCliCommand: vi.fn() };+});+const createFakeProc = ({exitCode = 0,stdoutChunks = [] as string[],@@ -263,6 +273,7 @@ describe('spawnAgent', () => {nextFakeProc = null;platformMock.mockReturnValue('linux');execFileMock.mockReset();+ detectHeterogeneousCliCommandMock.mockResolvedValue({ available: true, path: 'traecli' });});afterEach(async () => {@@ -513,6 +524,11 @@ describe('spawnAgent', () => {for await (const event of handle.events) events.push(event);await expect(handle.exit).resolves.toEqual({ code: 0, signal: null });+ expect(detectHeterogeneousCliCommandMock).toHaveBeenCalledWith(+ 'trae',+ 'traecli',+ expect.objectContaining({ PATH: process.env.PATH }),+ );expect(spawnCalls[0]).toMatchObject({args: ['acp', 'serve', '--yolo', '--feature=test'],command: 'traecli',@@ -537,7 +553,88 @@ describe('spawnAgent', () => {}});- it('does not treat the open-source trae-cli trajectory runner as TRAE ACP', async () => {+ it('allows the official canonical trae-cli command to run through ACP', async () => {+ const fake = createFakeAcpProc();+ nextFakeProc = fake.proc;+ detectHeterogeneousCliCommandMock.mockResolvedValue({+ available: true,+ path: '/usr/local/bin/trae-cli',+ });+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);++ try {+ const { spawnAgent } = await import('./spawnAgent');+ const handle = await spawnAgent({+ agentType: 'trae',+ command: 'trae-cli',+ env: { PATH: '/custom/node/bin' },+ operationId: 'op-trae',+ prompt: 'do a thing',+ });++ for await (const _event of handle.events) {+ // Consume the ACP session to completion.+ }+ await expect(handle.exit).resolves.toEqual({ code: 0, signal: null });+ expect(spawnCalls[0]).toMatchObject({+ args: ['acp', 'serve', '--yolo'],+ command: '/usr/local/bin/trae-cli',+ options: { env: { PATH: '/custom/node/bin' } },+ });+ expect(detectHeterogeneousCliCommandMock).toHaveBeenCalledWith(+ 'trae',+ 'trae-cli',+ expect.objectContaining({ PATH: '/custom/node/bin' }),+ );+ } finally {+ killSpy.mockRestore();+ }+ });++ it('resolves a relative TRAE command against the child working directory before probing', async () => {+ const cwd = await mkdtemp(path.join(os.tmpdir(), 'lobehub-trae-cwd-'));+ tempDirs.push(cwd);+ const relativeCommand = './bin/traecli';+ const resolvedCommand = path.resolve(cwd, relativeCommand);+ const fake = createFakeAcpProc();+ nextFakeProc = fake.proc;+ detectHeterogeneousCliCommandMock.mockImplementationOnce(async (_agentType, command) => ({+ available: true,+ path: command,+ }));+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);++ try {+ const { spawnAgent } = await import('./spawnAgent');+ const handle = await spawnAgent({+ agentType: 'trae',+ command: relativeCommand,+ cwd,+ operationId: 'op-trae-relative',+ prompt: 'do a thing',+ });++ for await (const _event of handle.events) {+ // Consume the ACP session to completion.+ }+ await expect(handle.exit).resolves.toEqual({ code: 0, signal: null });+ expect(detectHeterogeneousCliCommandMock).toHaveBeenCalledWith(+ 'trae',+ resolvedCommand,+ expect.objectContaining({ PATH: process.env.PATH }),+ );+ expect(spawnCalls[0]).toMatchObject({+ command: resolvedCommand,+ options: { cwd },+ });+ } finally {+ killSpy.mockRestore();+ }+ });++ it('rejects a custom TRAE command that does not expose the ACP runtime', async () => {+ detectHeterogeneousCliCommandMock.mockResolvedValue({ available: false });+const { spawnAgent } = await import('./spawnAgent');await expect(@@ -547,7 +644,12 @@ describe('spawnAgent', () => {operationId: 'op-trae',prompt: 'do a thing',}),- ).rejects.toThrow('trajectory runner is unsupported');+ ).rejects.toThrow('TRAE command does not expose the required ACP runtime: trae-cli');+ expect(detectHeterogeneousCliCommandMock).toHaveBeenCalledWith(+ 'trae',+ 'trae-cli',+ expect.objectContaining({ PATH: process.env.PATH }),+ );expect(spawnCalls).toHaveLength(0);});diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 441be14707a..e40d4fdac0c 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -1,6 +1,7 @@import type { ChildProcess } from 'node:child_process';import { spawn } from 'node:child_process';import { existsSync } from 'node:fs';+import path from 'node:path';import { PassThrough } from 'node:stream';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';@@ -8,7 +9,7 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { resolveHeterogeneousAgentCommand } from '../config';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';import { HETERO_WORKING_DIRECTORY_NOT_FOUND } from './classifyProcessFailure';-import { resolveCliSpawnPlan } from './cliSpawn';+import { isPathLikeCommand, resolveCliSpawnPlan } from './cliSpawn';import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';import { buildGrokAcpPrompt, GrokAcpSession } from './grokAcpSession';import type { AgentPromptInput, BuildAgentInputOptions } from './input';@@ -727,18 +728,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent/** Spawn TRAE's bidirectional ACP runtime behind the ordinary SpawnAgentHandle contract. */export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentHandle> => {- const command = resolveHeterogeneousAgentCommand('trae', options.command);- const commandName = command- .trim()- .split(/[\\/]/)- .at(-1)- ?.replace(/\.(?:bat|cmd|exe)$/i, '');- if (commandName?.toLowerCase() === 'trae-cli') {- throw new Error(- 'The open-source `trae-cli` trajectory runner is unsupported; install TRAE Enterprise `traecli` instead.',- );- }-+ const requestedCommand = resolveHeterogeneousAgentCommand('trae', options.command);const cwd = options.cwd || process.cwd();if (!existsSync(cwd)) {throw Object.assign(new Error(`Working directory does not exist: ${cwd}`), {@@ -746,6 +736,16 @@ export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<SpaworkingDirectory: cwd,});}+ const command =+ isPathLikeCommand(requestedCommand) && !path.isAbsolute(requestedCommand)+ ? path.resolve(cwd, requestedCommand)+ : requestedCommand;+ const childEnv = { ...process.env, ...options.env };+ const { detectHeterogeneousCliCommand } = await import('./resolveCliCommand');+ const commandStatus = await detectHeterogeneousCliCommand('trae', command, childEnv);+ if (!commandStatus.available || !commandStatus.path) {+ throw new Error(`TRAE command does not expose the required ACP runtime: ${requestedCommand}`);+ }const prompt = await buildTraeAcpPrompt(options.prompt, options.inputOptions);const stderr = new PassThrough();@@ -761,9 +761,12 @@ export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<Spaconst session = new TraeAcpSession({args: options.extraArgs ?? [],clientVersion: '1.0.0',- commandPath: command,+ commandPath: commandStatus.path,cwd,- env: { ...process.env, ...options.env },+ env: {+ ...childEnv,+ ...(commandStatus.resolvedPathEnv ? { PATH: commandStatus.resolvedPathEnv } : {}),+ },initialModel: options.initialModel,onEvents: (events) => {queue.push(...events);