🤯 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(agent): detect installed OpenClaw and Hermes (#18646)
AmAzing-0a44f1b23fdc
diff --git a/apps/cli/src/tools/__tests__/checkPlatformCapability.test.ts b/apps/cli/src/tools/__tests__/checkPlatformCapability.test.tsnew file mode 100644index 00000000000..4e578c8c037--- /dev/null+++ b/apps/cli/src/tools/__tests__/checkPlatformCapability.test.ts@@ -0,0 +1,56 @@+import { resolveRemotePlatformCommand } from '@lobechat/heterogeneous-agents/scanHost';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { checkPlatformCapability } from '../checkPlatformCapability';++vi.mock('@lobechat/heterogeneous-agents/scanHost', () => ({+ resolveRemotePlatformCommand: vi.fn(),+}));++const resolveRemotePlatformCommandMock = vi.mocked(resolveRemotePlatformCommand);++describe('checkPlatformCapability', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('reports the shared resolver result instead of probing a bare command', async () => {+ resolveRemotePlatformCommandMock.mockResolvedValue({+ available: true,+ path: '/Users/x/.openclaw/bin/openclaw',+ resolvedPathEnv: '/opt/homebrew/bin:/usr/bin:/bin',+ version: '2026.1.29',+ });++ await expect(checkPlatformCapability({ platform: 'openclaw' })).resolves.toEqual({+ available: true,+ version: '2026.1.29',+ });+ expect(resolveRemotePlatformCommandMock).toHaveBeenCalledWith('openclaw');+ });++ it('preserves the shared validation failure reason', async () => {+ resolveRemotePlatformCommandMock.mockResolvedValue({+ available: false,+ error: 'hermes was not found or failed validation',+ });++ await expect(checkPlatformCapability({ platform: 'hermes' })).resolves.toEqual({+ available: false,+ reason: 'hermes was not found or failed validation',+ });+ });++ it('rejects an unsupported runtime platform', async () => {+ resolveRemotePlatformCommandMock.mockResolvedValue({+ available: false,+ error: 'Unknown platform: future-platform',+ });++ await expect(checkPlatformCapability({ platform: 'future-platform' })).resolves.toEqual({+ available: false,+ reason: 'Unknown platform: future-platform',+ });+ expect(resolveRemotePlatformCommandMock).toHaveBeenCalledWith('future-platform');+ });+});diff --git a/apps/cli/src/tools/__tests__/getAgentProfile.test.ts b/apps/cli/src/tools/__tests__/getAgentProfile.test.tsnew file mode 100644index 00000000000..8983215a727--- /dev/null+++ b/apps/cli/src/tools/__tests__/getAgentProfile.test.ts@@ -0,0 +1,80 @@+import { resolveRemotePlatformRuntime } from '@lobechat/heterogeneous-agents/scanHost';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getAgentProfile } from '../getAgentProfile';++vi.mock('node:fs', () => ({+ default: {+ existsSync: vi.fn(() => true),+ readFileSync: vi.fn(() => '# Soul\nA careful systems engineer.'),+ },+}));++vi.mock('@lobechat/heterogeneous-agents/scanHost', () => ({+ resolveRemotePlatformRuntime: vi.fn(),+}));++const executeMock = vi.fn();+const resolveRemotePlatformRuntimeMock = vi.mocked(resolveRemotePlatformRuntime);++const queueExecResult = (stdout: string) => {+ executeMock.mockResolvedValueOnce({ stderr: '', stdout });+};++describe('getAgentProfile', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resolveRemotePlatformRuntimeMock.mockResolvedValue({+ available: true,+ execute: executeMock,+ prepareSpawn: vi.fn(),+ });+ });++ it('uses the shared OpenClaw execution runtime', async () => {+ queueExecResult(+ JSON.stringify([+ {+ id: 'main',+ identityEmoji: '🦞',+ identityName: 'Claw',+ isDefault: true,+ },+ ]),+ );++ await expect(getAgentProfile({ platform: 'openclaw' })).resolves.toEqual({+ avatar: '🦞',+ description: undefined,+ title: 'Claw',+ });+ expect(resolveRemotePlatformRuntimeMock).toHaveBeenCalledWith('openclaw');+ expect(executeMock).toHaveBeenCalledWith(['agents', 'list', '--json'], { timeout: 5000 });+ });++ it('uses one shared Hermes runtime for both profile probes', async () => {+ queueExecResult(' ◆default\n');+ queueExecResult('Path: ~/.hermes/profiles/default\n');++ await expect(getAgentProfile({ platform: 'hermes' })).resolves.toEqual({+ avatar: '⚡',+ description: 'A careful systems engineer.',+ title: 'default',+ });+ expect(resolveRemotePlatformRuntimeMock).toHaveBeenCalledTimes(1);+ expect(executeMock).toHaveBeenNthCalledWith(1, ['profile', 'list'], { timeout: 5000 });+ expect(executeMock).toHaveBeenNthCalledWith(2, ['profile', 'show', 'default'], {+ timeout: 5000,+ });+ });++ it('does not run a bare command when resolution fails', async () => {+ resolveRemotePlatformRuntimeMock.mockResolvedValue({+ available: false,+ error: 'openclaw was not found or failed validation',+ });++ await expect(getAgentProfile({ platform: 'openclaw' })).resolves.toEqual({});+ expect(executeMock).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/tools/__tests__/heteroTask.test.ts b/apps/cli/src/tools/__tests__/heteroTask.test.tsindex 4ec23ec435c..5b55d61a259 100644--- a/apps/cli/src/tools/__tests__/heteroTask.test.ts+++ b/apps/cli/src/tools/__tests__/heteroTask.test.ts@@ -10,12 +10,18 @@ const spawnMock = vi.hoisted(() => vi.fn());const execFileSyncMock = vi.hoisted(() => vi.fn());const fsState = vi.hoisted(() => ({ content: undefined as string | undefined }));const notifyMutateMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const prepareSpawnMock = vi.hoisted(() => vi.fn());+const resolveRemotePlatformRuntimeMock = vi.hoisted(() => vi.fn());vi.mock('node:child_process', () => ({execFileSync: execFileSyncMock,spawn: spawnMock,}));+vi.mock('@lobechat/heterogeneous-agents/scanHost', () => ({+ resolveRemotePlatformRuntime: resolveRemotePlatformRuntimeMock,+}));+vi.mock('node:fs', () => ({default: {mkdirSync: vi.fn(),@@ -56,6 +62,26 @@ vi.mock('../../utils/logger', () => ({log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },}));+beforeEach(() => {+ resolveRemotePlatformRuntimeMock.mockImplementation(+ async (type: 'hermes' | 'openclaw', baseEnv: NodeJS.ProcessEnv) => ({+ available: true,+ execute: vi.fn(),+ prepareSpawn: (args: string[]) => prepareSpawnMock(type, args, baseEnv),+ }),+ );+ prepareSpawnMock.mockImplementation(+ async (type: 'hermes' | 'openclaw', args: string[], baseEnv: NodeJS.ProcessEnv) => ({+ args,+ command: `/resolved/bin/${type}`,+ env: {+ ...baseEnv,+ PATH: '/resolved/bin:/runtime/bin:/usr/bin',+ },+ }),+ );+});+// ─── Helpers ───function resetTrpcClientMock() {@@ -326,6 +352,36 @@ describe('runHeteroTask (openclaw)', () => {expect(spawnArgs).toContain('--local');});+ it('spawns the resolved OpenClaw executable with its recovered PATH', async () => {+ const child = makeMockChild();+ spawnMock.mockReturnValue(child);++ await runHeteroTask({+ agentType: 'openclaw',+ operationId: 'op-resolved',+ prompt: 'hello',+ taskId: 'task-resolved',+ topicId: 'topic-resolved',+ });++ expect(resolveRemotePlatformRuntimeMock).toHaveBeenCalledWith(+ 'openclaw',+ expect.objectContaining({ LOBEHUB_OPERATION_ID: 'op-resolved' }),+ );+ expect(prepareSpawnMock).toHaveBeenCalledWith(+ 'openclaw',+ expect.any(Array),+ expect.objectContaining({ LOBEHUB_OPERATION_ID: 'op-resolved' }),+ );+ expect(spawnMock).toHaveBeenCalledWith(+ '/resolved/bin/openclaw',+ expect.any(Array),+ expect.objectContaining({+ env: expect.objectContaining({ PATH: '/resolved/bin:/runtime/bin:/usr/bin' }),+ }),+ );+ });+it('removes task and ignores already-exited process when killing concurrent task', async () => {const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => {throw new Error('No such process');@@ -534,6 +590,36 @@ describe('runHeteroTask (hermes)', () => {});});+ it('spawns the resolved Hermes executable with its recovered PATH', async () => {+ const child = makeMockChild();+ spawnMock.mockReturnValue(child);++ await runHeteroTask({+ agentType: 'hermes',+ operationId: 'op-resolved',+ prompt: 'hello',+ taskId: 'task-resolved',+ topicId: 'topic-resolved',+ });++ expect(resolveRemotePlatformRuntimeMock).toHaveBeenCalledWith(+ 'hermes',+ expect.objectContaining({ LOBEHUB_OPERATION_ID: 'op-resolved' }),+ );+ expect(prepareSpawnMock).toHaveBeenCalledWith(+ 'hermes',+ ['chat', '--query', 'hello', '--quiet', '--accept-hooks'],+ expect.objectContaining({ LOBEHUB_OPERATION_ID: 'op-resolved' }),+ );+ expect(spawnMock).toHaveBeenCalledWith(+ '/resolved/bin/hermes',+ expect.any(Array),+ expect.objectContaining({+ env: expect.objectContaining({ PATH: '/resolved/bin:/runtime/bin:/usr/bin' }),+ }),+ );+ });+it('resumes the saved session and replaces it with a continuation id', async () => {const firstChild = makeMockChild(1001);const secondChild = makeMockChild(1002);diff --git a/apps/cli/src/tools/checkPlatformCapability.ts b/apps/cli/src/tools/checkPlatformCapability.tsindex bbfb214a94f..ef0d31570d3 100644--- a/apps/cli/src/tools/checkPlatformCapability.ts+++ b/apps/cli/src/tools/checkPlatformCapability.ts@@ -1,7 +1,7 @@-import { execFileSync } from 'node:child_process';+import { resolveRemotePlatformCommand } from '@lobechat/heterogeneous-agents/scanHost';export interface CheckPlatformCapabilityParams {- platform: 'hermes' | 'openclaw';+ platform: string;}export interface CheckPlatformCapabilityResult {@@ -14,48 +14,21 @@ export interface CheckPlatformCapabilityResult {* Probe whether a specific agent platform is available on this device.* Dispatched by the server via `device.checkCapability` tRPC procedure.*- * - openclaw: runs `openclaw --version` and parses the output- * - hermes: hits the gateway health endpoint on the configured port+ * Uses the same validated executable and PATH recovery as host scanning,+ * profile lookup, and task execution so these surfaces cannot disagree.*/export async function checkPlatformCapability(params: CheckPlatformCapabilityParams,): Promise<CheckPlatformCapabilityResult> {const { platform } = params;+ const status = await resolveRemotePlatformCommand(platform);- if (platform === 'openclaw') {- try {- const output = execFileSync('openclaw', ['--version'], {- encoding: 'utf8',- timeout: 5000,- }).trim();- // output is typically "openclaw x.y.z"- const version = output.split(/\s+/).at(-1);- return { available: true, version };- } catch (err) {- return {- available: false,- reason: err instanceof Error ? err.message : 'openclaw not found or failed to run',- };- }+ if (!status.available) {+ return {+ available: false,+ reason: status.error ?? `${platform} was not found or failed validation`,+ };}- if (platform === 'hermes') {- try {- const output = execFileSync('hermes', ['--version'], {- encoding: 'utf8',- timeout: 5000,- }).trim();- // output is typically "Hermes Agent vX.Y.Z (...)"- const versionMatch = output.match(/v(\d+\.\d+\.\d+)/);- const version = versionMatch ? versionMatch[1] : output.split(/\s+/).at(-1);- return { available: true, version };- } catch (err) {- return {- available: false,- reason: err instanceof Error ? err.message : 'hermes not found or failed to run',- };- }- }-- return { available: false, reason: `Unknown platform: ${platform as string}` };+ return status.version ? { available: true, version: status.version } : { available: true };}diff --git a/apps/cli/src/tools/getAgentProfile.ts b/apps/cli/src/tools/getAgentProfile.tsindex 3f50a127ecc..eb02eaa2ccd 100644--- a/apps/cli/src/tools/getAgentProfile.ts+++ b/apps/cli/src/tools/getAgentProfile.ts@@ -1,9 +1,10 @@-import { execFileSync } from 'node:child_process';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import type { RemoteHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import type { RemotePlatformCommandRuntime } from '@lobechat/heterogeneous-agents/scanHost';+import { resolveRemotePlatformRuntime } from '@lobechat/heterogeneous-agents/scanHost';export interface GetAgentProfileParams {/** Agent ID to query (openclaw only). Defaults to the default agent. */@@ -48,13 +49,23 @@ interface OpenClawAgentEntry {workspace?: string;}-function getOpenClawProfile(agentId?: string): AgentProfileResult {+type AvailableRemotePlatformRuntime = Extract<RemotePlatformCommandRuntime, { available: true }>;++async function runPlatformCommand(+ runtime: AvailableRemotePlatformRuntime,+ args: string[],+): Promise<string> {+ const { stdout } = await runtime.execute(args, { timeout: 5000 });+ return stdout;+}++async function getOpenClawProfile(+ runtime: AvailableRemotePlatformRuntime,+ agentId?: string,+): Promise<AgentProfileResult> {let output: string;try {- output = execFileSync('openclaw', ['agents', 'list', '--json'], {- encoding: 'utf8',- timeout: 5000,- });+ output = await runPlatformCommand(runtime, ['agents', 'list', '--json']);} catch {return {};}@@ -85,12 +96,11 @@ function getOpenClawProfile(agentId?: string): AgentProfileResult {* Read the active Hermes profile name from `hermes profile list` output.* The active profile is marked with ◆ in the first column.*/-function getActiveHermesProfileName(): string | undefined {+async function getActiveHermesProfileName(+ runtime: AvailableRemotePlatformRuntime,+): Promise<string | undefined> {try {- const output = execFileSync('hermes', ['profile', 'list'], {- encoding: 'utf8',- timeout: 5000,- });+ const output = await runPlatformCommand(runtime, ['profile', 'list']);const match = output.match(/◆(\S+)/);return match?.[1];} catch {@@ -101,12 +111,12 @@ function getActiveHermesProfileName(): string | undefined {/*** Read the filesystem path of a Hermes profile from `hermes profile show <name>`.*/-function getHermesProfilePath(profileName: string): string | undefined {+async function getHermesProfilePath(+ runtime: AvailableRemotePlatformRuntime,+ profileName: string,+): Promise<string | undefined> {try {- const output = execFileSync('hermes', ['profile', 'show', profileName], {- encoding: 'utf8',- timeout: 5000,- });+ const output = await runPlatformCommand(runtime, ['profile', 'show', profileName]);const match = output.match(/^Path:\s+(.+)/m);const raw = match?.[1]?.trim();// Expand leading `~` — Node does not auto-expand home-dir shorthands.@@ -144,11 +154,13 @@ function readHermesSoulDescription(soulPath: string): string | undefined {}}-function getHermesProfile(): AgentProfileResult {- const profileName = getActiveHermesProfileName();+async function getHermesProfile(+ runtime: AvailableRemotePlatformRuntime,+): Promise<AgentProfileResult> {+ const profileName = await getActiveHermesProfileName(runtime);if (!profileName) return {};- const profilePath = getHermesProfilePath(profileName);+ const profilePath = await getHermesProfilePath(runtime, profileName);const description = profilePath? readHermesSoulDescription(path.join(profilePath, 'SOUL.md')): undefined;@@ -170,13 +182,15 @@ function getHermesProfile(): AgentProfileResult {*/export async function getAgentProfile(params: GetAgentProfileParams): Promise<AgentProfileResult> {const { platform, agentId } = params;+ const runtime = await resolveRemotePlatformRuntime(platform);+ if (!runtime.available) return {};if (platform === 'openclaw') {- return getOpenClawProfile(agentId);+ return getOpenClawProfile(runtime, agentId);}if (platform === 'hermes') {- return getHermesProfile();+ return getHermesProfile(runtime);}return {};diff --git a/apps/cli/src/tools/heteroTask.ts b/apps/cli/src/tools/heteroTask.tsindex 2fee588e445..1dd91d44a7c 100644--- a/apps/cli/src/tools/heteroTask.ts+++ b/apps/cli/src/tools/heteroTask.ts@@ -4,6 +4,7 @@ import os from 'node:os';import path from 'node:path';import type { RemoteHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import { resolveRemotePlatformRuntime } from '@lobechat/heterogeneous-agents/scanHost';import { getTrpcClient } from '../api/client';import { CLI_PRODUCT_NAME, resolveCliDirName } from '../constants/identity';@@ -197,15 +198,30 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<stringconst sessionKey = parentOperationId ? operationId : topicId;if (agentType === 'openclaw') {+ const runtime = await resolveRemotePlatformRuntime('openclaw', childEnv);+ if (!runtime.available) {+ throw new Error('OpenClaw executable not found');+ }+// openclaw agent --local is one-shot: each invocation processes one message and exits.// The --session-id links turns into the same conversation history on disk.- // Requires the `openclaw` binary to be on PATH with Node >=22.19.const openclawAgent = platformAgentId?.trim() || process.env.OPENCLAW_AGENT_ID || 'main';// Always inject the notify protocol so openclaw knows how to report results// back to the LobeHub UI — even if the previous turn failed and the session// history was not cleanly committed.const enrichedPrompt = `${prompt}\n\n${buildNotifyProtocol(lhPath, topicId)}`;+ const openclawArgs = [+ 'agent',+ '--agent',+ openclawAgent,+ '--session-id',+ sessionKey,+ '--message',+ enrichedPrompt,+ '--local',+ ];+ const spawnPlan = await runtime.prepareSpawn(openclawArgs);// Top-level turns reuse one topic session and replace an older process. Group// members intentionally share a topic, so isolate them by operation instead.@@ -226,25 +242,12 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string}}- const child = spawn(- 'openclaw',- [- 'agent',- '--agent',- openclawAgent,- '--session-id',- sessionKey,- '--message',- enrichedPrompt,- '--local',- ],- {- cwd: workDir,- detached: true,- env: childEnv,- stdio: 'ignore',- },- );+ const child = spawn(spawnPlan.command, spawnPlan.args, {+ cwd: workDir,+ detached: true,+ env: spawnPlan.env,+ stdio: 'ignore',+ });const pid = child.pid;if (pid === undefined) {@@ -302,6 +305,19 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string}if (agentType === 'hermes') {+ const runtime = await resolveRemotePlatformRuntime('hermes', childEnv);+ if (!runtime.available) {+ throw new Error('Hermes executable not found');+ }++ // Resume the previous session for this topic if one exists.+ const existingSessionId = getHermesSessionId(sessionKey);+ const hermesArgs: string[] = ['chat', '--query', prompt, '--quiet', '--accept-hooks'];+ if (existingSessionId) {+ hermesArgs.push('--resume', existingSessionId);+ }+ const spawnPlan = await runtime.prepareSpawn(hermesArgs);+// Preserve parallel group members; only top-level turns replace the previous// topic process, while an exact task retry replaces itself.for (const existing of listTasks()) {@@ -319,19 +335,12 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string}}- // Resume the previous session for this topic if one exists.- const existingSessionId = getHermesSessionId(sessionKey);- const hermesArgs: string[] = ['chat', '--query', prompt, '--quiet', '--accept-hooks'];- if (existingSessionId) {- hermesArgs.push('--resume', existingSessionId);- }-// Hermes keeps stdout response-only in --quiet mode and prints the final// session_id to stderr so callers can resume the session on the next turn.- const child = spawn('hermes', hermesArgs, {+ const child = spawn(spawnPlan.command, spawnPlan.args, {cwd: workDir,detached: true,- env: childEnv,+ env: spawnPlan.env,stdio: ['ignore', 'pipe', 'pipe'],});diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 8f7268178f0..cd753863935 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -6,9 +6,12 @@ import path from 'node:path';import type { DeviceControlDeps } from '@lobechat/device-control';import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';-import { resolveRemotePlatformCommand } from '@lobechat/heterogeneous-agents/scanHost';+import type { RemotePlatformCommandRuntime } from '@lobechat/heterogeneous-agents/scanHost';+import {+ resolveRemotePlatformCommand,+ resolveRemotePlatformRuntime,+} from '@lobechat/heterogeneous-agents/scanHost';import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';-import { execa } from 'execa';import GatewayConnectionService from '@/services/gatewayConnectionSrv';import ImessageBridgeService from '@/services/imessageBridgeSrv';@@ -25,6 +28,8 @@ import ShellCommandCtr from './ShellCommandCtr';const logger = createLogger('controllers:GatewayConnectionCtr');+type AvailableRemotePlatformRuntime = Extract<RemotePlatformCommandRuntime, { available: true }>;+// Mirror of `BrowserManifest.identifier` from `@lobechat/builtin-tool-browser`.// Hardcoded (not imported) so the desktop main process keeps zero builtin-tool// package deps — importing one risks the @lobechat/types stub runtime leak.@@ -517,20 +522,12 @@ export default class GatewayConnectionCtr extends ControllerModule {platform: string;}): Promise<{ available: boolean; reason?: string; version?: string }> {const { platform } = args;-- const platformMap: Record<string, 'hermes' | 'openclaw'> = {- hermes: 'hermes',- openclaw: 'openclaw',- };-- const platformType = platformMap[platform];- if (!platformType) {- return { available: false, reason: `Unknown platform: ${platform}` };- }-- const status = await resolveRemotePlatformCommand(platformType);+ const status = await resolveRemotePlatformCommand(platform);if (!status.available) {- return { available: false, reason: `${platform} is not installed on this device` };+ return {+ available: false,+ reason: status.error ?? `${platform} is not installed on this device`,+ };}return status.version ? { available: true, version: status.version } : { available: true };@@ -542,24 +539,25 @@ export default class GatewayConnectionCtr extends ControllerModule {title?: string;}> {const { platform, agentId } = args;+ if (platform !== 'openclaw' && platform !== 'hermes') return {};- if (platform === 'openclaw') {- return this.getOpenClawProfile(agentId);- }+ const runtime = await resolveRemotePlatformRuntime(platform);+ if (!runtime.available) return {};- if (platform === 'hermes') {- return this.getHermesProfile();+ if (platform === 'openclaw') {+ return this.getOpenClawProfile(runtime, agentId);}- return {};+ return this.getHermesProfile(runtime);}- private getHermesProfile(): { avatar?: string; description?: string; title?: string } {+ private async getHermesProfile(+ runtime: AvailableRemotePlatformRuntime,+ ): Promise<{ avatar?: string; description?: string; title?: string }> {// Find the active profile (marked with ◆ in `hermes profile list`).let profileName: string | undefined;try {- const listOutput = execFileSync('hermes', ['profile', 'list'], {- encoding: 'utf8',+ const { stdout: listOutput } = await runtime.execute(['profile', 'list'], {timeout: 5000,});profileName = listOutput.match(/◆(\S+)/)?.[1];@@ -571,8 +569,7 @@ export default class GatewayConnectionCtr extends ControllerModule {// Get the profile's filesystem path.let profilePath: string | undefined;try {- const showOutput = execFileSync('hermes', ['profile', 'show', profileName], {- encoding: 'utf8',+ const { stdout: showOutput } = await runtime.execute(['profile', 'show', profileName], {timeout: 5000,});const raw = showOutput.match(/^Path:\s+(.+)/m)?.[1]?.trim();@@ -612,17 +609,16 @@ export default class GatewayConnectionCtr extends ControllerModule {}}- private getOpenClawProfile(agentId?: string): {- avatar?: string;- description?: string;- title?: string;- } {+ private async getOpenClawProfile(+ runtime: AvailableRemotePlatformRuntime,+ agentId?: string,+ ): Promise<{ avatar?: string; description?: string; title?: string }> {let output: string;try {- output = execFileSync('openclaw', ['agents', 'list', '--json'], {- encoding: 'utf8',+ const result = await runtime.execute(['agents', 'list', '--json'], {timeout: 5000,});+ output = result.stdout;} catch {return {};}@@ -720,11 +716,10 @@ export default class GatewayConnectionCtr extends ControllerModule {const sessionKey = parentOperationId ? operationId : topicId;if (agentType === 'openclaw') {- const commandStatus = await resolveRemotePlatformCommand('openclaw');- if (!commandStatus.available || !commandStatus.path) {+ const runtime = await resolveRemotePlatformRuntime('openclaw', childEnv);+ if (!runtime.available) {throw new Error('OpenClaw executable not found');}- if (commandStatus.resolvedPathEnv) childEnv.PATH = commandStatus.resolvedPathEnv;const lhPath = this.resolveLhPath();const openclawAgent = platformAgentId?.trim() || process.env['OPENCLAW_AGENT_ID'] || 'main';@@ -757,21 +752,13 @@ export default class GatewayConnectionCtr extends ControllerModule {enrichedPrompt,'--local',];- const child =- process.platform === 'win32'- ? execa(commandStatus.path, openclawArgs, {- cwd: workDir,- detached: true,- env: childEnv,- reject: false,- stdio: 'ignore',- })- : spawn(commandStatus.path, openclawArgs, {- cwd: workDir,- detached: true,- env: childEnv,- stdio: 'ignore',- });+ const spawnPlan = await runtime.prepareSpawn(openclawArgs);+ const child = spawn(spawnPlan.command, spawnPlan.args, {+ cwd: workDir,+ detached: true,+ env: spawnPlan.env,+ stdio: 'ignore',+ });const pid = child.pid;if (pid === undefined) throw new Error('Failed to get PID for openclaw process');@@ -836,11 +823,10 @@ export default class GatewayConnectionCtr extends ControllerModule {}if (agentType === 'hermes') {- const commandStatus = await resolveRemotePlatformCommand('hermes');- if (!commandStatus.available || !commandStatus.path) {+ const runtime = await resolveRemotePlatformRuntime('hermes', childEnv);+ if (!runtime.available) {throw new Error('Hermes executable not found');}- if (commandStatus.resolvedPathEnv) childEnv.PATH = commandStatus.resolvedPathEnv;// Kill any existing hermes process for this topicId before spawning a new one.for (const [existingTaskId, entry] of this.platformTasks) {if (@@ -862,23 +848,13 @@ export default class GatewayConnectionCtr extends ControllerModule {// Hermes keeps stdout response-only in --quiet mode and prints the final// session_id to stderr so callers can resume the session on the next turn.- const child =- process.platform === 'win32'- ? execa(commandStatus.path, hermesArgs, {- cwd: workDir,- detached: true,- env: childEnv,- reject: false,- stderr: 'pipe',- stdin: 'ignore',- stdout: 'pipe',- })- : spawn(commandStatus.path, hermesArgs, {- cwd: workDir,- detached: true,- env: childEnv,- stdio: ['ignore', 'pipe', 'pipe'],- });+ const spawnPlan = await runtime.prepareSpawn(hermesArgs);+ const child = spawn(spawnPlan.command, spawnPlan.args, {+ cwd: workDir,+ detached: true,+ env: spawnPlan.env,+ stdio: ['ignore', 'pipe', 'pipe'],+ });const pid = child.pid;if (pid === undefined) throw new Error('Failed to get PID for hermes process');diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex 4fe10c9a97a..8e58b8f84c9 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -185,7 +185,10 @@ vi.mock('node:crypto', () => ({const execFileSyncMock = vi.hoisted(() => vi.fn());const spawnMock = vi.hoisted(() => vi.fn());+const executeRemotePlatformMock = vi.hoisted(() => vi.fn());+const prepareRemotePlatformSpawnMock = vi.hoisted(() => vi.fn());const resolveRemotePlatformCommandMock = vi.hoisted(() => vi.fn());+const resolveRemotePlatformRuntimeMock = vi.hoisted(() => vi.fn());vi.mock('node:child_process', async (importOriginal) => {const actual = await importOriginal<typeof ChildProcessModule>();@@ -194,6 +197,7 @@ vi.mock('node:child_process', async (importOriginal) => {vi.mock('@lobechat/heterogeneous-agents/scanHost', () => ({resolveRemotePlatformCommand: resolveRemotePlatformCommandMock,+ resolveRemotePlatformRuntime: resolveRemotePlatformRuntimeMock,}));vi.mock('node:os', () => ({@@ -208,10 +212,6 @@ vi.mock('@/services/imessageBridgeSrv', () => ({default: class ImessageBridgeService {},}));-vi.mock('execa', () => ({- execa: vi.fn().mockResolvedValue({ stdout: '', stderr: '' }),-}));-vi.mock('fast-glob', () => ({ default: vi.fn().mockResolvedValue([]) }));vi.mock('fflate', () => ({ unzipSync: vi.fn() }));@@ -300,6 +300,21 @@ describe('GatewayConnectionCtr', () => {beforeEach(() => {vi.clearAllMocks();vi.useFakeTimers();+ resolveRemotePlatformRuntimeMock.mockImplementation(+ async (type: 'hermes' | 'openclaw', baseEnv: NodeJS.ProcessEnv = process.env) => ({+ available: true,+ execute: executeRemotePlatformMock,+ prepareSpawn: (args: string[]) => prepareRemotePlatformSpawnMock(type, args, baseEnv),+ }),+ );+ prepareRemotePlatformSpawnMock.mockImplementation(+ async (type: 'hermes' | 'openclaw', args: string[], baseEnv: NodeJS.ProcessEnv) => ({+ args,+ command: `/resolved/bin/${type}`,+ env: { ...baseEnv, PATH: '/resolved/bin:/usr/bin' },+ }),+ );+ executeRemotePlatformMock.mockResolvedValue({ stderr: '', stdout: '' });MockGatewayClient.lastInstance = null;MockGatewayClient.lastOptions = null;mockStoreGet.mockImplementation((key: string) => {@@ -1052,12 +1067,6 @@ describe('GatewayConnectionCtr', () => {beforeEach(() => {execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');- resolveRemotePlatformCommandMock.mockResolvedValue({- available: true,- path: '/resolved/bin/openclaw',- resolvedPathEnv: '/resolved/bin:/usr/bin',- version: '1.2.3',- });spawnMock.mockReset();});@@ -1439,15 +1448,6 @@ describe('GatewayConnectionCtr', () => {});describe('hermes', () => {- beforeEach(() => {- resolveRemotePlatformCommandMock.mockResolvedValue({- available: true,- path: '/resolved/bin/hermes',- resolvedPathEnv: '/resolved/bin:/usr/bin',- version: '0.20.0',- });- });-it('relays stdout intact and saves the final session id from stderr', async () => {const child = makeMockChild();const notifySpy = vi.spyOn(ctr as any, 'sendNotify').mockResolvedValue(undefined);@@ -1657,6 +1657,11 @@ describe('GatewayConnectionCtr', () => {});it('returns available:false for unknown platform', async () => {+ resolveRemotePlatformCommandMock.mockResolvedValue({+ available: false,+ error: 'Unknown platform: unknownBot',+ });+const client = await connectAndOpen();client.simulateToolCallRequest('checkPlatformCapability',@@ -1676,6 +1681,11 @@ describe('GatewayConnectionCtr', () => {});it('getAgentProfile returns empty object', async () => {+ resolveRemotePlatformRuntimeMock.mockResolvedValue({+ available: false,+ error: 'openclaw was not found or failed validation',+ });+const client = await connectAndOpen();client.simulateToolCallRequest('getAgentProfile', { platform: 'openclaw' }, 'req-profile');await vi.advanceTimersByTimeAsync(0);@@ -1688,6 +1698,66 @@ describe('GatewayConnectionCtr', () => {success: true,},});+ expect(executeRemotePlatformMock).not.toHaveBeenCalled();+ });++ it('uses the shared OpenClaw runtime to load its profile', async () => {+ executeRemotePlatformMock.mockResolvedValueOnce({+ stderr: '',+ stdout: JSON.stringify([+ {+ id: 'main',+ identityEmoji: '🦞',+ identityName: 'Clawd',+ isDefault: true,+ },+ ]),+ });++ const client = await connectAndOpen();+ client.simulateToolCallRequest('getAgentProfile', { platform: 'openclaw' }, 'req-openclaw');+ await vi.advanceTimersByTimeAsync(0);++ expect(resolveRemotePlatformRuntimeMock).toHaveBeenCalledWith('openclaw');+ expect(executeRemotePlatformMock).toHaveBeenCalledWith(['agents', 'list', '--json'], {+ timeout: 5000,+ });+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({+ requestId: 'req-openclaw',+ result: {+ content: JSON.stringify({ avatar: '🦞', title: 'Clawd' }),+ state: { avatar: '🦞', description: undefined, title: 'Clawd' },+ success: true,+ },+ });+ });++ it('uses one shared Hermes runtime to load its profile', async () => {+ executeRemotePlatformMock+ .mockResolvedValueOnce({ stderr: '', stdout: '◆research\n' })+ .mockResolvedValueOnce({ stderr: '', stdout: 'Path: /profiles/research\n' });++ const client = await connectAndOpen();+ client.simulateToolCallRequest('getAgentProfile', { platform: 'hermes' }, 'req-hermes');+ await vi.advanceTimersByTimeAsync(0);++ expect(resolveRemotePlatformRuntimeMock).toHaveBeenCalledWith('hermes');+ expect(executeRemotePlatformMock).toHaveBeenNthCalledWith(1, ['profile', 'list'], {+ timeout: 5000,+ });+ expect(executeRemotePlatformMock).toHaveBeenNthCalledWith(+ 2,+ ['profile', 'show', 'research'],+ { timeout: 5000 },+ );+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({+ requestId: 'req-hermes',+ result: {+ content: JSON.stringify({ avatar: '⚡', title: 'research' }),+ state: { avatar: '⚡', description: undefined, title: 'research' },+ success: true,+ },+ });});});diff --git a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.tsindex 73487244e3f..02b79f7038b 100644--- a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts+++ b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts@@ -263,20 +263,21 @@ describe('cliAgentBinaries', () => {});it('reports unavailable when `where` only returns unrunnable matches (.ps1 / extensionless)', async () => {- callExecFile(- [- 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude',- 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.ps1',- ].join('\r\n'),- );+ const unrunnableMatches = [+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude',+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.ps1',+ ];+ callExecFile(unrunnableMatches.join('\r\n'));const { claudeCodeBinary } = await import('../cliAgentBinaries');const status = await claudeCodeBinary.detect();expect(status.available).toBe(false);- // Must not attempt to invoke the unrunnable matches.+ // PATH recovery may issue registry queries and retry `where`, but must+ // never attempt to invoke either unrunnable result.expect(execMock).not.toHaveBeenCalled();- expect(execFileMock).toHaveBeenCalledTimes(1); // just `where`+ const invokedFiles = execFileMock.mock.calls.map(([file]) => file);+ for (const match of unrunnableMatches) expect(invokedFiles).not.toContain(match);});});@@ -475,8 +476,14 @@ describe('cliAgentBinaries', () => {const status = await detectHeterogeneousCliCommand('codex', '/custom/bin/codex');expect(status.available).toBe(false);- // Only the explicit path's --version attempt — no fallback probing.- expect(execFileMock).toHaveBeenCalledTimes(1);+ // PATH recovery may retry the explicit launcher in a second environment,+ // but every version probe must keep that launcher rather than switching+ // to a built-in Codex fallback.+ const versionProbeFiles = execFileMock.mock.calls+ .filter(([, args]) => Array.isArray(args) && args.includes('--version'))+ .map(([file]) => file);+ expect(versionProbeFiles.length).toBeGreaterThan(0);+ expect(versionProbeFiles).toEqual(versionProbeFiles.map(() => '/custom/bin/codex'));});it('falls back to the login shell PATH for tools installed by shell setup', async () => {diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.tsindex 51c6e200d50..b4cc0576f3f 100644--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts@@ -352,11 +352,25 @@ describe('heterogeneous agent model discovery', () => {it('keeps the resolver login-shell PATH when the caller also provides PATH', async () => {const originalShell = process.env.SHELL;process.env.SHELL = '/bin/zsh';- rejectExecFile(new Error('not on inherited PATH'));- resolveExecFile('/login/bin:/usr/bin');- resolveExecFile('/login/bin/opencode\n');- resolveExecFile('1.18.3');- resolveExecFile('openai/gpt-5.6\n');+ execFileMock.mockImplementation(((+ file: string,+ args: string[],+ options: any,+ callback: any,+ ) => {+ if (file === '/bin/zsh') {+ callback(null, { stderr: '', stdout: '/login/bin:/usr/bin' });+ } else if (file === 'which' && options.env?.PATH?.includes('/login/bin')) {+ callback(null, { stderr: '', stdout: '/login/bin/opencode\n' });+ } else if (file === '/login/bin/opencode' && args.includes('--version')) {+ callback(null, { stderr: '', stdout: '1.18.3' });+ } else if (file === '/login/bin/opencode' && args.includes('models')) {+ callback(null, { stderr: '', stdout: 'openai/gpt-5.6\n' });+ } else {+ callback(new Error('unavailable in inherited environment'), { stderr: '', stdout: '' });+ }+ return {} as any;+ }) as any);try {const { listHeterogeneousAgentModels } = await importModule();diff --git a/packages/heterogeneous-agents/src/scan/scanHost.test.ts b/packages/heterogeneous-agents/src/scan/scanHost.test.tsindex 99db7b2fd13..7b669b3cfb9 100644--- a/packages/heterogeneous-agents/src/scan/scanHost.test.ts+++ b/packages/heterogeneous-agents/src/scan/scanHost.test.ts@@ -1,24 +1,53 @@+import * as childProcess from 'node:child_process';+import * as os from 'node:os';+import path from 'node:path';+import { beforeEach, describe, expect, it, vi } from 'vitest';-import { probeRemotePlatform, resolveRemotePlatformCommand } from './scanHost';+import {+ probeRemotePlatform,+ resolveRemotePlatformCommand,+ resolveRemotePlatformRuntime,+} from './scanHost';++vi.mock('node:child_process', () => ({ execFile: vi.fn() }));++vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof os>('node:os');+ return { ...actual, platform: vi.fn(() => 'darwin') };+});-const { detectHeterogeneousCliCommandMock, detectValidatedCommandMock } = vi.hoisted(() => ({+const {+ detectHeterogeneousCliCommandMock,+ detectValidatedCommandCandidatesMock,+ resolveCliSpawnPlanMock,+} = vi.hoisted(() => ({detectHeterogeneousCliCommandMock: vi.fn(),- detectValidatedCommandMock: vi.fn(),+ detectValidatedCommandCandidatesMock: vi.fn(),+ resolveCliSpawnPlanMock: vi.fn(),}));vi.mock('../spawn/resolveCliCommand', () => ({detectHeterogeneousCliCommand: detectHeterogeneousCliCommandMock,- detectValidatedCommand: detectValidatedCommandMock,+ detectValidatedCommandCandidates: detectValidatedCommandCandidatesMock,}));+vi.mock('../spawn/cliSpawn', () => ({+ resolveCliSpawnPlan: resolveCliSpawnPlanMock,+}));++const platformMock = vi.mocked(os.platform);+const execFileMock = vi.mocked(childProcess.execFile);+describe('platform command scanning', () => {beforeEach(() => {vi.clearAllMocks();+ platformMock.mockReturnValue('darwin');+ resolveCliSpawnPlanMock.mockImplementation(async (command, args) => ({ args, command }));});it('uses the shared PATH and Windows-shim-aware command resolver', async () => {- detectValidatedCommandMock.mockResolvedValue({+ detectValidatedCommandCandidatesMock.mockResolvedValue({available: true,path: '/resolved/bin/openclaw',resolvedPathEnv: '/resolved/bin:/usr/bin',@@ -31,13 +60,90 @@ describe('platform command scanning', () => {resolvedPathEnv: '/resolved/bin:/usr/bin',version: '1.2.3',});- expect(detectValidatedCommandMock).toHaveBeenCalledWith('openclaw', {- validateKeywords: ['openclaw'],+ expect(detectValidatedCommandCandidatesMock).toHaveBeenCalledWith(+ [+ 'openclaw',+ path.join(os.homedir(), '.openclaw', 'bin', 'openclaw'),+ path.join(os.homedir(), '.local', 'bin', 'openclaw'),+ ],+ {+ validateHelpKeywords: ['Usage: openclaw'],+ validateKeywords: ['openclaw'],+ validatePattern: expect.any(RegExp),+ },+ );+ });++ it('accepts the bare version banner printed by OpenClaw 2026.1.29', async () => {+ detectValidatedCommandCandidatesMock.mockImplementation(async (_commands, options) => ({+ available: options.validatePattern.test('2026.1.29'),+ path: '/resolved/bin/openclaw',+ version: '2026.1.29',+ }));++ await expect(resolveRemotePlatformCommand('openclaw')).resolves.toMatchObject({+ available: true,+ version: '2026.1.29',+ });+ });++ it('rejects unsupported platforms before probing any command', async () => {+ await expect(resolveRemotePlatformCommand('future-platform')).resolves.toEqual({+ available: false,+ error: 'Unknown platform: future-platform',+ });+ expect(detectValidatedCommandCandidatesMock).not.toHaveBeenCalled();+ });++ it('rejects a Windows shim that cannot produce a shell-free spawn plan', async () => {+ platformMock.mockReturnValue('win32');+ detectValidatedCommandCandidatesMock.mockResolvedValue({+ available: true,+ path: String.raw`C:\Users\x\AppData\Roaming\npm\openclaw.cmd`,+ version: '2026.1.29',+ });++ await expect(resolveRemotePlatformCommand('openclaw')).resolves.toEqual({+ available: false,+ error: 'openclaw was not found or failed validation',+ });+ });++ it('falls back to the official OpenClaw managed install path', async () => {+ detectValidatedCommandCandidatesMock.mockResolvedValue({+ available: true,+ path: path.join(os.homedir(), '.openclaw', 'bin', 'openclaw'),+ version: '2026.1.29',+ });++ await expect(resolveRemotePlatformCommand('openclaw')).resolves.toMatchObject({+ available: true,+ version: '2026.1.29',+ });+ expect(detectValidatedCommandCandidatesMock.mock.calls[0]![0]).toContain(+ path.join(os.homedir(), '.openclaw', 'bin', 'openclaw'),+ );+ });++ it('falls back to the official Hermes user-local install path', async () => {+ detectValidatedCommandCandidatesMock.mockResolvedValue({+ available: true,+ path: path.join(os.homedir(), '.local', 'bin', 'hermes'),+ version: '0.20.5',+ });++ await expect(resolveRemotePlatformCommand('hermes')).resolves.toMatchObject({+ available: true,+ version: '0.20.5',});+ expect(detectValidatedCommandCandidatesMock.mock.calls[0]![0]).toEqual([+ 'hermes',+ path.join(os.homedir(), '.local', 'bin', 'hermes'),+ ]);});it('keeps host scan responses free of executable paths', async () => {- detectValidatedCommandMock.mockResolvedValue({+ detectValidatedCommandCandidatesMock.mockResolvedValue({available: true,path: '/private/bin/hermes',resolvedPathEnv: '/private/bin:/usr/bin',@@ -49,4 +155,88 @@ describe('platform command scanning', () => {version: '0.9.0',});});++ it('binds spawn preparation to the validated executable and recovered PATH', async () => {+ detectValidatedCommandCandidatesMock.mockResolvedValue({+ available: true,+ path: '/resolved/bin/openclaw',+ resolvedPathEnv: '/runtime/bin:/usr/bin',+ version: '2026.1.29',+ });+ const baseEnv: NodeJS.ProcessEnv = {+ ...process.env,+ AUTH_TOKEN: 'token',+ PATH: '/stale/bin:/usr/bin',+ };++ const runtime = await resolveRemotePlatformRuntime('openclaw', baseEnv);+ expect(runtime.available).toBe(true);+ if (!runtime.available) return;++ await expect(runtime.prepareSpawn(['agent', '--local'])).resolves.toEqual({+ args: ['agent', '--local'],+ command: '/resolved/bin/openclaw',+ env: expect.objectContaining({+ AUTH_TOKEN: 'token',+ PATH: '/runtime/bin:/usr/bin',+ }),+ });+ expect(resolveCliSpawnPlanMock).toHaveBeenCalledWith(+ '/resolved/bin/openclaw',+ ['agent', '--local'],+ expect.objectContaining({+ AUTH_TOKEN: 'token',+ PATH: '/runtime/bin:/usr/bin',+ }),+ );+ });++ it('executes one-shot commands through the prepared runtime plan', async () => {+ detectValidatedCommandCandidatesMock.mockResolvedValue({+ available: true,+ path: '/resolved/bin/hermes',+ resolvedPathEnv: '/runtime/bin:/usr/bin',+ });+ resolveCliSpawnPlanMock.mockImplementation(async (command, args) =>+ args.length === 0+ ? { args, command }+ : { args: ['/runtime/hermes.js', ...args], command: '/runtime/node' },+ );+ execFileMock.mockImplementationOnce(((+ _command: string,+ _args: string[],+ _options: object,+ callback: (error: null, stdout: string, stderr: string) => void,+ ) => {+ callback(null, '◆default\n', 'diagnostic\n');+ return {};+ }) as never);++ const runtime = await resolveRemotePlatformRuntime('hermes');+ expect(runtime.available).toBe(true);+ if (!runtime.available) return;++ await expect(runtime.execute(['profile', 'list'], { timeout: 1234 })).resolves.toEqual({+ stderr: 'diagnostic\n',+ stdout: '◆default\n',+ });+ expect(execFileMock).toHaveBeenCalledWith(+ '/runtime/node',+ ['/runtime/hermes.js', 'profile', 'list'],+ expect.objectContaining({+ env: expect.objectContaining({ PATH: '/runtime/bin:/usr/bin' }),+ timeout: 1234,+ }),+ expect.any(Function),+ );+ });++ it('surfaces the platform validation failure reason', async () => {+ detectValidatedCommandCandidatesMock.mockResolvedValue({ available: false });++ await expect(probeRemotePlatform('hermes')).resolves.toEqual({+ available: false,+ reason: 'hermes was not found or failed validation',+ });+ });});diff --git a/packages/heterogeneous-agents/src/scan/scanHost.ts b/packages/heterogeneous-agents/src/scan/scanHost.tsindex 1ea347d1861..03b2577c314 100644--- a/packages/heterogeneous-agents/src/scan/scanHost.ts+++ b/packages/heterogeneous-agents/src/scan/scanHost.ts@@ -1,7 +1,15 @@-import type { RemoteHeterogeneousAgentType } from '../config';+import { execFile } from 'node:child_process';+import { homedir, platform } from 'node:os';+import path from 'node:path';++import type { RemoteHeterogeneousAgentDescriptor, RemoteHeterogeneousAgentType } from '../config';import { HETEROGENEOUS_AGENT_CONFIGS, REMOTE_HETEROGENEOUS_AGENT_CONFIGS } from '../config';+import { resolveCliSpawnPlan } from '../spawn/cliSpawn';import type { CliCommandStatus } from '../spawn/resolveCliCommand';-import { detectHeterogeneousCliCommand, detectValidatedCommand } from '../spawn/resolveCliCommand';+import {+ detectHeterogeneousCliCommand,+ detectValidatedCommandCandidates,+} from '../spawn/resolveCliCommand';import type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './types';/**@@ -12,15 +20,159 @@ import type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './* (`@lobechat/heterogeneous-agents/scanHost`), never from a browser bundle.*/+const getRemotePlatformConfig = (type: string): RemoteHeterogeneousAgentDescriptor | undefined =>+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS.find((config) => config.type === type);++const getRemotePlatformCommandCandidates = (+ config: RemoteHeterogeneousAgentDescriptor,+): string[] => {+ if (platform() !== 'darwin' && platform() !== 'linux') return [config.cli.command];++ return [+ config.cli.command,+ ...(config.cli.wellKnownHomePaths ?? []).map((relativePath) =>+ path.join(homedir(), ...relativePath.split('/')),+ ),+ ];+};++const buildRemotePlatformEnvironment = (+ status: CliCommandStatus,+ baseEnv: NodeJS.ProcessEnv,+): NodeJS.ProcessEnv => ({+ ...baseEnv,+ ...(status.resolvedPathEnv && { PATH: status.resolvedPathEnv }),+});++const isUnresolvedWindowsShim = (command: string): boolean =>+ platform() === 'win32' && /\.(?:bat|cmd)$/i.test(command);+/*** Resolve and validate a notify-based platform executable using the same* login-shell PATH and Windows npm-shim handling as the CLI agent resolver.- * Spawn sites must use the returned absolute path and `resolvedPathEnv` too;- * otherwise a packaged Electron app can detect a command that it cannot run.+ * This is the detection/capability boundary; execution sites must use+ * `resolveRemotePlatformRuntime` so the validated path and environment cannot+ * be separated.*/-export const resolveRemotePlatformCommand = async (- type: RemoteHeterogeneousAgentType,-): Promise<CliCommandStatus> => detectValidatedCommand(type, { validateKeywords: [type] });+export const resolveRemotePlatformCommand = async (type: string): Promise<CliCommandStatus> => {+ const config = getRemotePlatformConfig(type);+ if (!config) return { available: false, error: `Unknown platform: ${type}` };++ const { helpKeywords, keywords, pattern: validationPattern } = config.cli.validation;+ const validation = {+ ...(helpKeywords && { validateHelpKeywords: [...helpKeywords] }),+ ...(keywords && { validateKeywords: [...keywords] }),+ ...(validationPattern && { validatePattern: new RegExp(validationPattern) }),+ };++ const status = await detectValidatedCommandCandidates(+ getRemotePlatformCommandCandidates(config),+ validation,+ );+ if (status.available && status.path) {+ try {+ const spawnPlan = await resolveCliSpawnPlan(+ status.path,+ [],+ buildRemotePlatformEnvironment(status, process.env),+ );+ if (!isUnresolvedWindowsShim(spawnPlan.command)) return status;+ } catch {+ // A command that validates but cannot produce a shell-free spawn plan is+ // not executable by a task. Report it unavailable so scan and execution+ // cannot disagree.+ }+ }++ return {+ available: false,+ error: `${type} was not found or failed validation`,+ };+};++export interface RemotePlatformCommandOutput {+ stderr: string;+ stdout: string;+}++export interface RemotePlatformSpawnPlan {+ args: string[];+ command: string;+ env: NodeJS.ProcessEnv;+}++export type RemotePlatformCommandRuntime =+ | {+ available: false;+ error: string;+ }+ | {+ available: true;+ execute: (+ args: string[],+ options?: { timeout?: number },+ ) => Promise<RemotePlatformCommandOutput>;+ prepareSpawn: (args: string[]) => Promise<RemotePlatformSpawnPlan>;+ version?: string;+ };++const executeSpawnPlan = (+ spawnPlan: RemotePlatformSpawnPlan,+ timeout = 5000,+): Promise<RemotePlatformCommandOutput> =>+ new Promise((resolve, reject) => {+ execFile(+ spawnPlan.command,+ spawnPlan.args,+ {+ encoding: 'utf8',+ env: spawnPlan.env,+ timeout,+ windowsHide: true,+ },+ (error, stdout, stderr) => {+ if (error) {+ reject(error);+ return;+ }++ resolve({ stderr: stderr.toString(), stdout: stdout.toString() });+ },+ );+ });++/**+ * Resolve one validated platform executable and bind every execution to the+ * exact PATH that validated it. Consumers keep their own task lifecycle, but+ * cannot accidentally fall back to a bare command or skip Windows shim+ * expansion when preparing a child process.+ */+export const resolveRemotePlatformRuntime = async (+ type: string,+ baseEnv: NodeJS.ProcessEnv = process.env,+): Promise<RemotePlatformCommandRuntime> => {+ const status = await resolveRemotePlatformCommand(type);+ if (!status.available || !status.path) {+ return {+ available: false,+ error: status.error ?? `${type} was not found or failed validation`,+ };+ }++ const validatedPath = status.path;+ const env = buildRemotePlatformEnvironment(status, baseEnv);+ const prepareSpawn = async (args: string[]): Promise<RemotePlatformSpawnPlan> => ({+ ...(await resolveCliSpawnPlan(validatedPath, args, env)),+ env,+ });++ return {+ available: true,+ execute: async (args, options) => executeSpawnPlan(await prepareSpawn(args), options?.timeout),+ prepareSpawn,+ version: status.version,+ };+};export const probeRemotePlatform = async (type: RemoteHeterogeneousAgentType,@@ -28,7 +180,7 @@ export const probeRemotePlatform = async (const status = await resolveRemotePlatformCommand(type);return status.available? { available: true, version: status.version }- : { available: false, reason: `${type} not found or failed to run` };+ : { available: false, reason: status.error };};export const scanHeterogeneousAgentsOnHost = async (): Promise<HeterogeneousAgentScanMap> => {diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.test.tsindex f24e65993b3..1a8f2f87e7f 100644--- a/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts@@ -201,6 +201,7 @@ describe('cliSpawn', () => {platformMock.mockReturnValue('win32');const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\example-cli.cmd';const nodePath = 'C:\\Program Files\\nodejs\\node.exe';+ const recoveredEnv = { ...process.env, PATH: 'C:\\Program Files\\nodejs;C:\\Windows' };const scriptPath ='C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node_modules\\example-cli\\bin\\cli.js';existingPaths(shimPath, scriptPath);@@ -208,10 +209,11 @@ describe('cliSpawn', () => {readFileMock.mockResolvedValue('node "%dp0%\\node_modules\\example-cli\\bin\\cli.js" %*\r\n');const { resolveCliSpawnPlan } = await import('./cliSpawn');- await expect(resolveCliSpawnPlan(shimPath, ['--help'])).resolves.toEqual({+ await expect(resolveCliSpawnPlan(shimPath, ['--help'], recoveredEnv)).resolves.toEqual({args: [scriptPath, '--help'],command: nodePath,});+ expect(execFileMock.mock.calls[0]![2]).toMatchObject({ env: recoveredEnv });});it('resolves the npm generated %_prog% .cmd shim form used by Codex and Gemini', async () => {diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.tsindex d70cdc01b3c..427c2fd4fa6 100644--- a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.ts@@ -73,12 +73,16 @@ const fileExists = async (filePath: string): Promise<boolean> => {}};-const execFileString = async (command: string, args: string[]): Promise<string> =>+const execFileString = async (+ command: string,+ args: string[],+ env?: NodeJS.ProcessEnv,+): Promise<string> =>new Promise((resolve, reject) => {execFile(command,args,- { timeout: 3000, windowsHide: true },+ { env, timeout: 3000, windowsHide: true },(error: Error | null, stdout: string) => {if (error) {reject(error);@@ -138,12 +142,15 @@ const getExistingShimPathToken = async (return (await fileExists(resolvedPath)) ? resolvedPath : undefined;};-const resolveWindowsNodeCommand = async (shimPath: string): Promise<string | undefined> => {+const resolveWindowsNodeCommand = async (+ shimPath: string,+ env?: NodeJS.ProcessEnv,+): Promise<string | undefined> => {const localNodePath = path.win32.join(path.win32.dirname(shimPath), 'node.exe');if (await fileExists(localNodePath)) return localNodePath;try {- const stdout = await execFileString('where', ['node']);+ const stdout = await execFileString('where', ['node'], env);const candidates = stdout.split(/\r?\n/).map((line) => line.trim())@@ -155,10 +162,14 @@ const resolveWindowsNodeCommand = async (shimPath: string): Promise<string | und}};-const getNodeCommand = async (shimPath: string, token: string): Promise<string | undefined> => {+const getNodeCommand = async (+ shimPath: string,+ token: string,+ env?: NodeJS.ProcessEnv,+): Promise<string | undefined> => {const trimmedToken = token.trim().replaceAll(/^['"]|['"]$/g, '');if (/^node(?:\.exe)?$/i.test(trimmedToken) || /^%_prog%$/i.test(trimmedToken)) {- return resolveWindowsNodeCommand(shimPath);+ return resolveWindowsNodeCommand(shimPath, env);}const resolvedPath = await getExistingShimPathToken(shimPath, trimmedToken);@@ -171,8 +182,9 @@ const getNodeScriptTarget = async (shimPath: string,nodeToken: string,scriptToken: string,+ env?: NodeJS.ProcessEnv,): Promise<WindowsShimTarget | undefined> => {- const command = await getNodeCommand(shimPath, nodeToken);+ const command = await getNodeCommand(shimPath, nodeToken, env);if (!command) return;const scriptPath = await getExistingShimPathToken(shimPath, scriptToken);@@ -184,6 +196,7 @@ const getNodeScriptTarget = async (const inferWindowsNodeScriptFromShim = async (shimPath: string,source: string,+ env?: NodeJS.ProcessEnv,): Promise<WindowsShimTarget | undefined> => {const patterns: Array<RegExp | [RegExp, string]> = [/exec\s+"(\$basedir[^"]*node(?:\.exe)?)"\s+"([^"]+)"/i,@@ -202,7 +215,7 @@ const inferWindowsNodeScriptFromShim = async (const scriptToken = Array.isArray(pattern) ? match[2] : match[2];if (!nodeToken || !scriptToken) continue;- const target = await getNodeScriptTarget(shimPath, nodeToken, scriptToken);+ const target = await getNodeScriptTarget(shimPath, nodeToken, scriptToken, env);if (target) return target;}};@@ -227,6 +240,7 @@ const inferWindowsExecutableFromShim = async (const inferWindowsNpmShimTarget = async (shimPath: string,+ env?: NodeJS.ProcessEnv,): Promise<WindowsShimTarget | undefined> => {if (WINDOWS_EXE_EXT_PATTERN.test(shimPath)) return { command: shimPath };if (!(await fileExists(shimPath))) return;@@ -234,7 +248,7 @@ const inferWindowsNpmShimTarget = async (try {const source = await readFile(shimPath, 'utf8');return (- (await inferWindowsNodeScriptFromShim(shimPath, source)) ??+ (await inferWindowsNodeScriptFromShim(shimPath, source, env)) ??(await inferWindowsExecutableFromShim(shimPath, source)));} catch {@@ -244,9 +258,10 @@ const inferWindowsNpmShimTarget = async (const resolveWindowsBareCommand = async (command: string,+ env?: NodeJS.ProcessEnv,): Promise<WindowsShimTarget | undefined> => {try {- const stdout = await execFileString('where', [command]);+ const stdout = await execFileString('where', [command], env);const candidates = stdout.split(/\r?\n/).map((line) => line.trim())@@ -263,7 +278,7 @@ const resolveWindowsBareCommand = async (// breaks CLI launch. Same PATH-order rule already applied to detection// candidates in resolveCliCommand.ts (see #17376).for (const candidate of candidates) {- const target = await inferWindowsNpmShimTarget(candidate);+ const target = await inferWindowsNpmShimTarget(candidate, env);if (target) return target;}@@ -276,13 +291,14 @@ const resolveWindowsBareCommand = async (export const resolveCliSpawnPlan = async (command: string,args: string[],+ env?: NodeJS.ProcessEnv,): Promise<CliSpawnPlan> => {const trimmedCommand = command.trim();if (!isWindows() || !trimmedCommand) return { args, command };const target = isPathLikeCommand(trimmedCommand)- ? await inferWindowsNpmShimTarget(trimmedCommand)- : await resolveWindowsBareCommand(trimmedCommand);+ ? await inferWindowsNpmShimTarget(trimmedCommand, env)+ : await resolveWindowsBareCommand(trimmedCommand, env);const spawnPlan = target? { args: [...(target.argsPrefix ?? []), ...args], command: target.command }diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.tsindex d1ccf0e5e03..175f71ba394 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts@@ -353,7 +353,7 @@ build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);const { detectHeterogeneousCliCommand } = await importModule();const status = await detectHeterogeneousCliCommand('trae', 'traecli-renamed');- expect(status).toEqual({ available: false });+ expect(status.available).toBe(false);expect(execFileMock.mock.calls[2]![1]).toEqual(['acp', 'serve', '--help']);});@@ -382,6 +382,190 @@ build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);}});+ it('prefers the login-PATH command over an inherited absolute fallback', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ process.env.PATH = '/usr/bin:/bin';+ process.env.SHELL = '/bin/zsh';+ const loginPath = '/login/bin:/usr/bin:/bin';+ const loginCommand = '/login/bin/opencode';+ const fallbackPath = '/fallback/bin/opencode';++ execFileMock.mockImplementation(((file: string, args: any, opts: any, cb: any) => {+ const callback = typeof opts === 'function' ? opts : cb;+ if (file === '/bin/zsh') {+ callback(noErr, { stderr: '', stdout: loginPath });+ } else if (file === 'which' && opts.env?.PATH === loginPath) {+ callback(noErr, { stderr: '', stdout: `${loginCommand}\n` });+ } else if (file === 'which') {+ callback(new Error('not found'), { stderr: '', stdout: '' });+ } else if (file === loginCommand || file === fallbackPath) {+ callback(noErr, { stderr: '', stdout: '1.18.3' });+ } else {+ callback(new Error(`unexpected execFile: ${file}`), { stderr: '', stdout: '' });+ }+ return {} as any;+ }) as any);++ try {+ const { detectValidatedCommandCandidates } = await importModule();+ const status = await detectValidatedCommandCandidates(['opencode', fallbackPath], {+ validatePattern: /^v?\d+\.\d+\.\d+$/,+ });++ expect(status).toMatchObject({+ available: true,+ path: loginCommand,+ resolvedPathEnv: loginPath,+ });+ expect(execFileMock.mock.calls.map(([file]) => file)).not.toContain(fallbackPath);+ } finally {+ process.env.PATH = originalPath;+ process.env.SHELL = originalShell;+ }+ });++ it('keeps an inherited fallback available when the recovered environment would break it', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ process.env.PATH = '/usr/bin:/bin';+ process.env.SHELL = '/bin/zsh';+ const loginPath = '/broken/bin:/usr/bin:/bin';+ const fallbackPath = '/fallback/bin/opencode';++ execFileMock.mockImplementation(((file: string, args: any, opts: any, cb: any) => {+ const callback = typeof opts === 'function' ? opts : cb;+ if (file === '/bin/zsh') {+ callback(noErr, { stderr: '', stdout: loginPath });+ } else if (file === 'which') {+ callback(new Error('not found'), { stderr: '', stdout: '' });+ } else if (file === fallbackPath && opts.env?.PATH !== loginPath) {+ callback(noErr, { stderr: '', stdout: '1.18.3' });+ } else {+ callback(new Error('broken recovered environment'), { stderr: '', stdout: '' });+ }+ return {} as any;+ }) as any);++ try {+ const { detectValidatedCommandCandidates } = await importModule();+ const status = await detectValidatedCommandCandidates(['opencode', fallbackPath], {+ validatePattern: /^v?\d+\.\d+\.\d+$/,+ });++ expect(status).toMatchObject({ available: true, path: fallbackPath });+ expect(status.resolvedPathEnv).toBeUndefined();+ } finally {+ process.env.PATH = originalPath;+ process.env.SHELL = originalShell;+ }+ });++ it('carries the recovered login PATH into an absolute fallback launcher', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ process.env.PATH = '/usr/bin:/bin';+ process.env.SHELL = '/bin/zsh';+ const loginPath = '/opt/homebrew/bin:/usr/bin:/bin';+ const fallbackPath = path.join(os.homedir(), '.opencode', 'bin', 'opencode');++ try {+ callExecFileError(new Error('not found')); // which opencode (inherited PATH)+ callExecFile(loginPath); // login shell PATH contains node, not opencode+ callExecFileError(new Error('not found')); // which opencode (login PATH)+ callExecFileError(new Error('node not found')); // fallback under inherited PATH+ callExecFile('1.18.3'); // ~/.opencode/bin/opencode --version++ const { detectValidatedCommandCandidates } = await importModule();+ const status = await detectValidatedCommandCandidates(['opencode', fallbackPath], {+ validatePattern: /^v?\d+\.\d+\.\d+$/,+ });++ expect(status).toMatchObject({+ available: true,+ path: fallbackPath,+ resolvedPathEnv: loginPath,+ version: '1.18.3',+ });+ expect((execFileMock.mock.calls[4]![2] as { env: NodeJS.ProcessEnv }).env.PATH).toBe(+ loginPath,+ );+ } finally {+ process.env.PATH = originalPath;+ process.env.SHELL = originalShell;+ }+ });++ it('retries an explicit env-based launcher with the recovered login PATH', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ process.env.PATH = '/usr/bin:/bin';+ process.env.SHELL = '/bin/zsh';+ const commandPath = '/Users/x/.local/bin/opencode';+ const loginPath = '/opt/homebrew/bin:/usr/bin:/bin';++ try {+ callExecFileError(new Error('node not found')); // inherited PATH+ callExecFile(loginPath); // login shell exposes node+ callExecFile('1.18.3'); // exact same launcher under recovered PATH++ const { detectValidatedCommand } = await importModule();+ const status = await detectValidatedCommand(commandPath, {+ validatePattern: /^v?\d+\.\d+\.\d+$/,+ });++ expect(status).toMatchObject({+ available: true,+ path: commandPath,+ resolvedPathEnv: loginPath,+ version: '1.18.3',+ });+ expect((execFileMock.mock.calls[2]![2] as { env: NodeJS.ProcessEnv }).env.PATH).toBe(+ loginPath,+ );+ } finally {+ process.env.PATH = originalPath;+ process.env.SHELL = originalShell;+ }+ });++ it('recovers the login PATH after an inherited command fails validation', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ process.env.PATH = '/usr/local/bin:/usr/bin:/bin';+ process.env.SHELL = '/bin/zsh';+ const loginPath = '/opt/homebrew/bin:/usr/bin:/bin:/usr/local/bin';+ const fallbackPath = path.join(os.homedir(), '.opencode', 'bin', 'opencode');++ try {+ callExecFile('/usr/local/bin/opencode\n'); // inherited PATH finds a stale launcher+ callExecFileError(new Error('stale launcher')); // inherited launcher validation+ callExecFile('/opt/homebrew/bin:/usr/bin:/bin'); // login shell PATH+ callExecFile('/usr/local/bin/opencode\n'); // retry under the merged PATH+ callExecFileError(new Error('stale launcher')); // recovered lookup still resolves stale copy+ callExecFileError(new Error('node not found')); // fallback under inherited PATH+ callExecFile('1.18.3'); // ~/.opencode/bin/opencode --version++ const { detectValidatedCommandCandidates } = await importModule();+ const status = await detectValidatedCommandCandidates(['opencode', fallbackPath], {+ validatePattern: /^v?\d+\.\d+\.\d+$/,+ });++ expect(status).toMatchObject({+ available: true,+ path: fallbackPath,+ resolvedPathEnv: loginPath,+ version: '1.18.3',+ });+ expect((execFileMock.mock.calls[6]![2] as { env: NodeJS.ProcessEnv }).env.PATH).toBe(+ loginPath,+ );+ } finally {+ process.env.PATH = originalPath;+ process.env.SHELL = originalShell;+ }+ });+it('finds Kimi Code in its official user-local install path', async () => {const originalPath = process.env.PATH;const originalShell = process.env.SHELL;@@ -500,8 +684,8 @@ build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);callExecFile('/Users/x/.local/share/mise/shims/codex\n'); // which codex (login PATH)callExecFile('codex-cli 0.142.5');- const { detectHeterogeneousCliCommand } = await importModule();- const status = await detectHeterogeneousCliCommand('codex', 'codex');+ const { detectValidatedCommand } = await importModule();+ const status = await detectValidatedCommand('codex', { validateKeywords: ['codex'] });expect(status.available).toBe(true);expect(status.path).toBe('/Users/x/.local/share/mise/shims/codex');@@ -513,6 +697,40 @@ build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);process.env.SHELL = originalShell;}});++ it('re-reads the login-shell PATH on a later scan', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ process.env.PATH = '/usr/bin:/bin';+ process.env.SHELL = '/bin/zsh';++ try {+ const { detectValidatedCommand } = await importModule();+ const options = { validateKeywords: ['new-agent'] };++ callExecFileError(new Error('not found')); // which new-agent+ callExecFile('/usr/bin:/bin'); // login shell before installation+ expect((await detectValidatedCommand('new-agent', options)).available).toBe(false);++ callExecFileError(new Error('not found')); // inherited PATH is still stale+ callExecFile('/Users/x/.local/bin:/usr/bin:/bin'); // shell PATH after installation+ callExecFile('/Users/x/.local/bin/new-agent\n');+ callExecFile('new-agent 1.2.3');++ await expect(detectValidatedCommand('new-agent', options)).resolves.toMatchObject({+ available: true,+ path: '/Users/x/.local/bin/new-agent',+ resolvedPathEnv: '/Users/x/.local/bin:/usr/bin:/bin',+ version: '1.2.3',+ });+ expect(execFileMock.mock.calls.filter(([command]) => command === '/bin/zsh')).toHaveLength(+ 2,+ );+ } finally {+ process.env.PATH = originalPath;+ process.env.SHELL = originalShell;+ }+ });});describe('detectValidatedCommand — Windows npm shims', () => {@@ -726,6 +944,49 @@ build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);}});+ it('prefers a registry-PATH command over an inherited absolute fallback', async () => {+ const originalPath = process.env.PATH;+ process.env.PATH = 'C:\\Windows';+ const registryBin = 'C:\\registry\\bin';+ const registryCommand = `${registryBin}\\codex.exe`;+ const fallbackPath = 'C:\\fallback\\codex.exe';+ existingFiles({ [fallbackPath]: true, [registryCommand]: true });++ execFileMock.mockImplementation(((file: string, args: any, opts: any, cb: any) => {+ const callback = typeof opts === 'function' ? opts : cb;+ if (file === 'where' && opts.env?.PATH && opts.env.PATH !== process.env.PATH) {+ callback(noErr, { stderr: '', stdout: `${registryCommand}\r\n` });+ } else if (file === 'where') {+ callback(new Error('not found'), { stderr: '', stdout: '' });+ } else if (file === 'reg' && String(args[1]).includes('HKCU')) {+ callback(noErr, {+ stderr: '',+ stdout: `\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_SZ ${registryBin}\r\n`,+ });+ } else if (file === 'reg') {+ callback(new Error('no value'), { stderr: '', stdout: '' });+ } else if (file === registryCommand || file === fallbackPath) {+ callback(noErr, { stderr: '', stdout: 'codex-cli 0.147.0' });+ } else {+ callback(new Error(`unexpected execFile: ${file}`), { stderr: '', stdout: '' });+ }+ return {} as any;+ }) as any);++ try {+ const { detectValidatedCommandCandidates } = await importModule();+ const status = await detectValidatedCommandCandidates(['codex', fallbackPath], {+ validateKeywords: ['codex'],+ });++ expect(status).toMatchObject({ available: true, path: registryCommand });+ expect(status.resolvedPathEnv).toContain(registryBin);+ expect(execFileMock.mock.calls.map(([file]) => file)).not.toContain(fallbackPath);+ } finally {+ process.env.PATH = originalPath;+ }+ });+it('falls back to the Windows Codex app bundled CLI when nothing is on PATH', async () => {const originalLocalAppData = process.env.LOCALAPPDATA;const originalPath = process.env.PATH;diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex 729ce0d8af0..b0bfc0b2758 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -32,6 +32,7 @@ export type HeterogeneousCliAgentType = LocalHeterogeneousAgentType;*/export interface CliCommandStatus {available: boolean;+ error?: string;path?: string;/*** PATH used to resolve/validate the command, surfaced only when it differs@@ -61,6 +62,11 @@ interface ResolvedCommand {resolvedPathEnv?: string;}+interface RecoveredProbeEnvironment {+ env: NodeJS.ProcessEnv;+ resolvedPathEnv: string;+}+const VERSION_PATTERN = /v?(\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?)/;const extractVersion = (versionBanner: string): string | undefined =>@@ -138,8 +144,15 @@ const getLoginShellPath = async (): Promise<string | undefined> => {}};-const getCachedLoginShellPath = async (): Promise<string | undefined> => {- shellPathPromise ??= getLoginShellPath();+/**+ * Share one login-shell lookup between concurrent probes, but discard it once+ * settled. A later Rescan must observe PATH edits made by an installer while+ * the desktop app is already running.+ */+const getCurrentLoginShellPath = async (): Promise<string | undefined> => {+ shellPathPromise ??= getLoginShellPath().finally(() => {+ shellPathPromise = undefined;+ });return shellPathPromise;};@@ -198,7 +211,7 @@ const readMergedWindowsRegistryPath = async (): Promise<string | undefined> => {* answer for the process lifetime would re-create the staleness it fixes: a* CLI installed after the first failed scan would stay "not installed" until* the app restarted. `reg query` is a couple of short-lived processes, and it- * only runs when `where` already came up empty.+ * only runs after the complete inherited-environment pass fails.*/const getWindowsRegistryPath = async (): Promise<string | undefined> => {registryPathPromise ??= readMergedWindowsRegistryPath().finally(() => {@@ -221,6 +234,26 @@ const mergePathValues = (...values: Array<string | undefined>): string | undefinreturn segments.length > 0 ? segments.join(path.delimiter) : undefined;};+const recoverProbeEnvironment = async (+ probeEnv?: NodeJS.ProcessEnv,+): Promise<RecoveredProbeEnvironment | undefined> => {+ const recoveredPath = isWindows()+ ? await getWindowsRegistryPath()+ : await getCurrentLoginShellPath();+ const currentPath = probeEnv?.PATH ?? process.env.PATH;+ const resolvedPathEnv = mergePathValues(recoveredPath, currentPath);++ if (!resolvedPathEnv || resolvedPathEnv === currentPath) return;++ return {+ env: {+ ...(probeEnv ?? process.env),+ PATH: resolvedPathEnv,+ },+ resolvedPathEnv,+ };+};+const getCommandPathLines = async (whichCommand: 'where' | 'which',command: string,@@ -259,43 +292,14 @@ const resolveCommandCandidates = async (const trimmedCommand = command.trim();if (!trimmedCommand) return [];+ const resolvedPathEnv = probeEnv?.PATH === process.env.PATH ? undefined : probeEnv?.PATH;+if (isPathLikeCommand(trimmedCommand)) {- return [- {- env: probeEnv,- path: trimmedCommand,- resolvedPathEnv: probeEnv?.PATH === process.env.PATH ? undefined : probeEnv?.PATH,- },- ];+ return [{ env: probeEnv, path: trimmedCommand, resolvedPathEnv }];}const whichCommand = isWindows() ? 'where' : 'which';- 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,- // Windows re-reads the registry environment (the inherited block is a- // creation-time snapshot that never picks up a later install).- const recoveredPath = isWindows()- ? await getWindowsRegistryPath()- : await getCachedLoginShellPath();- const lookupPath = mergePathValues(recoveredPath, probeEnv?.PATH ?? process.env.PATH);-- if (lookupPath && lookupPath !== (probeEnv?.PATH ?? process.env.PATH)) {- const fallbackEnv = {- ...(probeEnv ?? process.env),- PATH: lookupPath,- };- lines = await getCommandPathLines(whichCommand, trimmedCommand, fallbackEnv);- if (lines) {- lookupEnv = fallbackEnv;- resolvedPathEnv = lookupPath;- }- }- }-+ const lines = await getCommandPathLines(whichCommand, trimmedCommand, probeEnv);if (!lines) return [];// Windows `where` lists every PATHEXT match (e.g. for `codex` npm ships a@@ -303,13 +307,13 @@ const resolveCommandCandidates = async (// ones we can execute, still in PATH order.if (isWindows()) {return pickWindowsRunnables(lines).map((runnablePath) => ({- env: lookupEnv,+ env: probeEnv,path: runnablePath,resolvedPathEnv,}));}- return [{ env: lookupEnv, path: lines[0], resolvedPathEnv }];+ return [{ env: probeEnv, path: lines[0], resolvedPathEnv }];};const quoteWindowsShellToken = (token: string): string =>@@ -375,7 +379,7 @@ const execProbe = async (});}- const spawnPlan = await resolveCliSpawnPlan(command, args);+ const spawnPlan = await resolveCliSpawnPlan(command, args, env);if (isWindows() && spawnPlan.command === command && isWindowsShimPath(command)) {return UNRESOLVED_SHIM;}@@ -392,7 +396,7 @@ const execProbe = async (* matching `--version` output against a keyword or output pattern (avoids* collisions with an unrelated executable of the same name).*/-export const detectValidatedCommand = async (+const detectValidatedCommandInEnvironment = async (command: string,options: ValidateOptions,probeEnv?: NodeJS.ProcessEnv,@@ -414,7 +418,10 @@ export const detectValidatedCommand = async (// 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, probeEnv);- if (candidates.length === 0) return { available: false };+ const resolvedPathEnv = probeEnv?.PATH === process.env.PATH ? undefined : probeEnv?.PATH;+ if (candidates.length === 0) {+ return resolvedPathEnv ? { available: false, resolvedPathEnv } : { available: false };+ }const validateCandidate = async ({ env, path: resolvedPath, resolvedPathEnv }: ResolvedCommand,@@ -517,9 +524,63 @@ export const detectValidatedCommand = async (if (status !== UNRESOLVED_SHIM && status.available) return status;}- return { available: false };+ return resolvedPathEnv ? { available: false, resolvedPathEnv } : { available: false };};+const isProbeableCommand = (command: string): boolean => {+ const trimmedCommand = command.trim();+ return trimmedCommand.length > 0 && !(isWindows() && WINDOWS_SHELL_METAS.test(trimmedCommand));+};++/**+ * Validate an ordered command chain with candidate precedence above environment+ * precedence: candidate 1 inherited → candidate 1 recovered → candidate 2+ * inherited → candidate 2 recovered. PATH recovery is attempted at most once+ * and reused, so lookup misses and validation failures share the same edge+ * without letting a well-known fallback outrank the user's login-PATH command.+ */+export const detectValidatedCommandCandidates = async (+ commands: string[],+ options: ValidateOptions,+ probeEnv?: NodeJS.ProcessEnv,+): Promise<CliCommandStatus> => {+ let lastStatus: CliCommandStatus = { available: false };+ let recoveryAttempted = false;+ let recovered: RecoveredProbeEnvironment | undefined;++ for (const command of commands) {+ const inheritedStatus = await detectValidatedCommandInEnvironment(command, options, probeEnv);+ if (inheritedStatus.available) return inheritedStatus;+ lastStatus = inheritedStatus;++ // Invalid Windows shell expressions must not trigger even the registry+ // helper processes used for PATH recovery.+ if (!isProbeableCommand(command)) continue;++ if (!recoveryAttempted) {+ recoveryAttempted = true;+ recovered = await recoverProbeEnvironment(probeEnv);+ }+ if (!recovered) continue;++ const recoveredStatus = await detectValidatedCommandInEnvironment(+ command,+ options,+ recovered.env,+ );+ if (recoveredStatus.available) return recoveredStatus;+ lastStatus = recoveredStatus;+ }++ return lastStatus;+};++export const detectValidatedCommand = async (+ command: string,+ options: ValidateOptions,+ probeEnv?: NodeJS.ProcessEnv,+): Promise<CliCommandStatus> => detectValidatedCommandCandidates([command], options, probeEnv);+const HETEROGENEOUS_CLI_AGENT_OPTIONS = {'amp': {validateFlag: '--help',@@ -742,22 +803,17 @@ export const detectHeterogeneousCliCommand = async (const validator = HETEROGENEOUS_CLI_AGENT_OPTIONS[agentType];if (!validator) return { available: false };- 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// location (e.g. the Codex desktop app's bundled CLI). Only probe those for the// default command: the well-known paths hold the *default* binary, so applying// them to a custom command (e.g. `claude-beta`) would silently resolve it to// 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, probeEnv);- if (fallbackStatus.available) return fallbackStatus;- }- }+ const commands =+ command.trim() === DEFAULT_HETERO_COMMAND[agentType]+ ? [command, ...getWellKnownCommandPaths(agentType)]+ : [command];- return status;+ return detectValidatedCommandCandidates(commands, validator, probeEnv);};/**diff --git a/packages/types/src/agent/heterogeneousAgent.ts b/packages/types/src/agent/heterogeneousAgent.tsindex a6b86538fa5..38546114502 100644--- a/packages/types/src/agent/heterogeneousAgent.ts+++ b/packages/types/src/agent/heterogeneousAgent.ts@@ -338,15 +338,48 @@ export const LOCAL_HETEROGENEOUS_AGENT_TYPES = HETEROGENEOUS_AGENT_CONFIGS.map((export const LocalHeterogeneousAgentTypeSchema = z.enum(LOCAL_HETEROGENEOUS_AGENT_TYPES);+export interface RemoteHeterogeneousAgentCliDescriptor {+ command: string;+ validation: {+ helpKeywords?: readonly string[];+ keywords?: readonly string[];+ pattern?: string;+ };+ wellKnownHomePaths?: readonly string[];+}+export interface RemoteHeterogeneousAgentDescriptor {+ cli: RemoteHeterogeneousAgentCliDescriptor;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' },+ {+ cli: {+ command: 'openclaw',+ validation: {+ helpKeywords: ['Usage: openclaw'],+ keywords: ['openclaw'],+ pattern: '^v?\\d+\\.\\d+\\.\\d+(?:[-+][\\dA-Za-z.-]+)?$',+ },+ wellKnownHomePaths: ['.openclaw/bin/openclaw', '.local/bin/openclaw'],+ },+ kind: 'remote-task',+ title: 'OpenClaw',+ type: 'openclaw',+ },+ {+ cli: {+ command: 'hermes',+ validation: { keywords: ['hermes'] },+ wellKnownHomePaths: ['.local/bin/hermes'],+ },+ kind: 'remote-task',+ title: 'Hermes',+ type: 'hermes',+ },] as const satisfies readonly RemoteHeterogeneousAgentDescriptor[];export type HeterogeneousAgentDescriptor =diff --git a/src/features/ConnectAgent/useAgentScan.test.ts b/src/features/ConnectAgent/useAgentScan.test.tsindex 46a6e73d0c7..5a8c4a6544e 100644--- a/src/features/ConnectAgent/useAgentScan.test.ts+++ b/src/features/ConnectAgent/useAgentScan.test.ts@@ -37,6 +37,28 @@ describe('scanLocal', () => {command: 'hermes',});});++ it('preserves detector and IPC failure reasons', async () => {+ detectHeterogeneousAgentCommand.mockImplementation(async ({ agentType }) => {+ if (agentType === 'openclaw') {+ return { available: false, error: 'openclaw failed validation' };+ }+ if (agentType === 'hermes') throw new Error('hermes scan timed out');+ return { available: false };+ });++ const agents = await scanLocal();++ expect(agents.openclaw).toEqual({+ available: false,+ reason: 'openclaw failed validation',+ version: undefined,+ });+ expect(agents.hermes).toEqual({+ available: false,+ reason: 'hermes scan timed out',+ });+ });});describe('buildPlatformAgencyConfig', () => {diff --git a/src/features/ConnectAgent/useAgentScan.ts b/src/features/ConnectAgent/useAgentScan.tsindex 8b7b3aa4fe0..40e89a6d9d4 100644--- a/src/features/ConnectAgent/useAgentScan.ts+++ b/src/features/ConnectAgent/useAgentScan.ts@@ -34,9 +34,19 @@ export const scanLocal = async (): Promise<HeterogeneousAgentScanMap> => {agentType: provider.type,command: provider.command ?? provider.type,});- return [provider.type, { available: status.available, version: status.version }] as const;- } catch {- return [provider.type, { available: false }] as const;+ return [+ provider.type,+ {+ available: status.available,+ ...(status.error ? { reason: status.error } : undefined),+ version: status.version,+ },+ ] as const;+ } catch (error) {+ return [+ provider.type,+ { available: false, reason: error instanceof Error ? error.message : String(error) },+ ] as const;}}),);