Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(desktop): replace ToolDetectorManager with BinaryManager + lazy install (#16439)

Innei50734a086223
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjs
index f63d902a0e9..14ff8d06e87 100644
--- a/apps/desktop/electron-builder.mjs
+++ b/apps/desktop/electron-builder.mjs
@@ -112,14 +112,16 @@ const config = {
await copyNativeModulesToSource();
await copyExternalRuntimeModulesToSource();
- console.info('πŸ“¦ Downloading agent-browser binary...');
- execSync('node scripts/download-agent-browser.mjs', { stdio: 'inherit', cwd: __dirname });
+ // agent-browser is no longer bundled in the installer β€” BinaryManager
+ // lazily downloads it on first use into the per-user cache dir. See
+ // apps/desktop/src/main/modules/binaries/agentBrowserBinaries.ts.
// Build and copy CLI bundle for embedding
console.info('πŸ“¦ Building CLI for embedding...');
execSync('npm run build:cli', { stdio: 'inherit', cwd: __dirname });
const cliSrc = path.resolve(__dirname, '../cli/dist/index.js');
const cliDest = path.resolve(__dirname, 'resources/bin/lobe-cli.js');
+ await fs.mkdir(path.dirname(cliDest), { recursive: true });
await fs.copyFile(cliSrc, cliDest);
// Write a minimal package.json next to the CLI bundle so that
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 280abbc1c31..9f1623d3de8 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -16,7 +16,6 @@
"build:run-unpack": "electron .",
"dev": "electron-vite dev",
"dev:static": "cross-env DESKTOP_RENDERER_STATIC=1 npm run dev",
- "download:agent-browser": "node scripts/download-agent-browser.mjs",
"format": "prettier --write ",
"i18n": "tsx scripts/i18nWorkflow/index.ts && lobe-i18n",
"postinstall": "electron-builder install-app-deps",
diff --git a/apps/desktop/scripts/download-agent-browser.mjs b/apps/desktop/scripts/download-agent-browser.mjs
deleted file mode 100644
index 13b99b009fe..00000000000
--- a/apps/desktop/scripts/download-agent-browser.mjs
+++ /dev/null
@@ -1,105 +0,0 @@
-import fs, { createWriteStream } from 'node:fs';
-import { chmod, mkdir, stat, writeFile } from 'node:fs/promises';
-import https from 'node:https';
-import path from 'node:path';
-import { pipeline } from 'node:stream/promises';
-import { fileURLToPath } from 'node:url';
-
-const VERSION = '0.24.0';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const binDir = path.join(__dirname, '..', 'resources', 'bin');
-const versionFile = path.join(binDir, '.agent-browser-version');
-
-const platformMap = { darwin: 'darwin', linux: 'linux', win32: 'win32' };
-const archMap = { arm64: 'arm64', x64: 'x64' };
-
-const platform = platformMap[process.platform];
-const arch = archMap[process.arch];
-
-console.info(`[agent-browser] platform=${process.platform} arch=${process.arch}`);
-console.info(`[agent-browser] target: ${platform}-${arch}`);
-console.info(`[agent-browser] binDir: ${binDir}`);
-
-if (!platform || !arch) {
- console.error(`[agent-browser] ❌ Unsupported platform: ${process.platform}-${process.arch}`);
- process.exit(1);
-}
-
-const isWindows = process.platform === 'win32';
-const binaryName = `agent-browser-${platform}-${arch}${isWindows ? '.exe' : ''}`;
-const outputName = `agent-browser${isWindows ? '.exe' : ''}`;
-const outputPath = path.join(binDir, outputName);
-
-// Check if already downloaded
-if (fs.existsSync(versionFile)) {
- const existing = fs.readFileSync(versionFile, 'utf8').trim();
- console.info(`[agent-browser] existing version: ${existing}, requested: ${VERSION}`);
- if (existing === VERSION && fs.existsSync(outputPath)) {
- const { size } = await stat(outputPath);
- console.info(
- `[agent-browser] βœ… v${VERSION} already present (${(size / 1024 / 1024).toFixed(1)} MB), skipping.`,
- );
- process.exit(0);
- }
-}
-
-const url = `https://github.com/vercel-labs/agent-browser/releases/download/v${VERSION}/${binaryName}`;
-
-console.info(`[agent-browser] ⬇️ Downloading v${VERSION}...`);
-console.info(`[agent-browser] URL: ${url}`);
-console.info(`[agent-browser] output: ${outputPath}`);
-
-await mkdir(binDir, { recursive: true });
-
-/**
- * Follow redirects and download to a writable stream.
- */
-function download(url, dest, maxRedirects = 5) {
- return new Promise((resolve, reject) => {
- if (maxRedirects <= 0) return reject(new Error('Too many redirects'));
-
- https
- .get(url, { headers: { 'User-Agent': 'lobehub-desktop' } }, (res) => {
- if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
- console.info(`[agent-browser] redirect β†’ ${res.headers.location}`);
- res.resume();
- return download(res.headers.location, dest, maxRedirects - 1).then(resolve, reject);
- }
-
- if (res.statusCode !== 200) {
- res.resume();
- return reject(new Error(`HTTP ${res.statusCode}`));
- }
-
- const contentLength = res.headers['content-length'];
- if (contentLength) {
- console.info(
- `[agent-browser] content-length: ${(contentLength / 1024 / 1024).toFixed(1)} MB`,
- );
- }
-
- const file = createWriteStream(dest);
- pipeline(res, file).then(resolve, reject);
- })
- .on('error', reject);
- });
-}
-
-try {
- await download(url, outputPath);
-
- const { size } = await stat(outputPath);
- console.info(`[agent-browser] downloaded ${(size / 1024 / 1024).toFixed(1)} MB`);
-
- if (!isWindows) {
- await chmod(outputPath, 0o755);
- console.info(`[agent-browser] chmod +x applied`);
- }
-
- await writeFile(versionFile, VERSION, 'utf8');
- console.info(`[agent-browser] βœ… v${VERSION} ready at ${outputPath}`);
-} catch (err) {
- console.error(`[agent-browser] ❌ Download failed: ${err.message}`);
- process.exit(1);
-}
diff --git a/apps/desktop/src/main/controllers/ToolDetectorCtr.ts b/apps/desktop/src/main/controllers/BinaryCtr.ts
similarity index 54%
rename from apps/desktop/src/main/controllers/ToolDetectorCtr.ts
rename to apps/desktop/src/main/controllers/BinaryCtr.ts
index 14a141873ff..5a0b73a34fb 100644
--- a/apps/desktop/src/main/controllers/ToolDetectorCtr.ts
+++ b/apps/desktop/src/main/controllers/BinaryCtr.ts
@@ -6,80 +6,83 @@ import type {
DetectHeterogeneousAgentCommandParams,
} from '@lobechat/electron-client-ipc';
-import type { ToolCategory, ToolStatus } from '@/core/infrastructure/ToolDetectorManager';
-import { detectHeterogeneousCliCommand } from '@/modules/toolDetectors';
+import type { BinaryCategory, BinaryStatus } from '@/core/infrastructure/BinaryManager';
+import { detectHeterogeneousCliCommand } from '@/modules/binaries';
import { createLogger } from '@/utils/logger';
import { ControllerModule, IpcMethod } from './index';
const execFilePromise = promisify(execFile);
-const logger = createLogger('controllers:ToolDetectorCtr');
+const logger = createLogger('controllers:BinaryCtr');
/**
- * Tool Detector Controller
+ * Binary Controller
*
- * Provides IPC interface for querying tool detection status.
- * Frontend can use these methods to display tool availability to users.
+ * Provides IPC interface for querying binary detection status.
+ * Frontend can use these methods to display binary availability to users.
*/
-export default class ToolDetectorCtr extends ControllerModule {
- static override readonly groupName = 'toolDetector';
+export default class BinaryCtr extends ControllerModule {
+ static override readonly groupName = 'binary';
private get manager() {
- return this.app.toolDetectorManager;
+ return this.app.binaryManager;
}
/**
- * Detect a single tool
+ * Detect a single binary
*/
@IpcMethod()
- async detectTool(name: string, force = false): Promise<ToolStatus> {
- logger.debug(`Detecting tool: ${name}, force: ${force}`);
+ async detect(name: string, force = false): Promise<BinaryStatus> {
+ logger.debug(`Detecting binary: ${name}, force: ${force}`);
return this.manager.detect(name, force);
}
@IpcMethod()
async detectHeterogeneousAgentCommand(
params: DetectHeterogeneousAgentCommandParams,
- ): Promise<ToolStatus> {
+ ): Promise<BinaryStatus> {
logger.debug('Detecting heterogeneous agent command:', params);
return detectHeterogeneousCliCommand(params.agentType, params.command);
}
/**
- * Detect all registered tools
+ * Detect all registered binaries
*/
@IpcMethod()
- async detectAllTools(force = false): Promise<Record<string, ToolStatus>> {
- logger.debug(`Detecting all tools, force: ${force}`);
+ async detectAll(force = false): Promise<Record<string, BinaryStatus>> {
+ logger.debug(`Detecting all binaries, force: ${force}`);
const results = await this.manager.detectAll(force);
return Object.fromEntries(results);
}
/**
- * Detect all tools in a category
+ * Detect all binaries in a category
*/
@IpcMethod()
- async detectCategory(category: ToolCategory, force = false): Promise<Record<string, ToolStatus>> {
+ async detectCategory(
+ category: BinaryCategory,
+ force = false,
+ ): Promise<Record<string, BinaryStatus>> {
logger.debug(`Detecting category: ${category}, force: ${force}`);
const results = await this.manager.detectCategory(category, force);
return Object.fromEntries(results);
}
/**
- * Get the best available tool in a category
+ * Get the best available binary in a category
*/
@IpcMethod()
- async getBestTool(category: ToolCategory): Promise<string | null> {
- logger.debug(`Getting best tool for category: ${category}`);
+ async getBestTool(category: BinaryCategory): Promise<string | null> {
+ logger.debug(`Getting best binary for category: ${category}`);
return this.manager.getBestTool(category);
}
/**
- * Get cached status for a tool (no detection)
+ * Get cached status for a binary (no detection)
*/
@IpcMethod()
- getToolStatus(name: string): ToolStatus | null {
+ getStatus(name: string): BinaryStatus | null {
return this.manager.getStatus(name) || null;
}
@@ -87,48 +90,48 @@ export default class ToolDetectorCtr extends ControllerModule {
* Get all cached statuses (no detection)
*/
@IpcMethod()
- getAllToolStatus(): Record<string, ToolStatus> {
+ getAllStatus(): Record<string, BinaryStatus> {
return Object.fromEntries(this.manager.getAllStatus());
}
/**
- * Clear tool status cache
+ * Clear binary status cache
*/
@IpcMethod()
- clearToolCache(name?: string): void {
+ clearCache(name?: string): void {
this.manager.clearCache(name);
- logger.debug(`Cleared tool cache${name ? ` for: ${name}` : ''}`);
+ logger.debug(`Cleared binary cache${name ? ` for: ${name}` : ''}`);
}
/**
- * Get list of registered tools
+ * Get list of registered binary names
*/
@IpcMethod()
- getRegisteredTools(): string[] {
- return this.manager.getRegisteredTools();
+ getRegistered(): string[] {
+ return this.manager.getRegistered();
}
/**
* Get all categories
*/
@IpcMethod()
- getCategories(): ToolCategory[] {
+ getCategories(): BinaryCategory[] {
return this.manager.getCategories();
}
/**
- * Get tools in a category with their info
+ * Get binaries in a category with their info
*/
@IpcMethod()
- getToolsInCategory(category: ToolCategory): Array<{
+ getInCategory(category: BinaryCategory): Array<{
description?: string;
name: string;
priority?: number;
}> {
- return this.manager.getToolsInCategory(category).map((detector) => ({
- description: detector.description,
- name: detector.name,
- priority: detector.priority,
+ return this.manager.getInCategory(category).map((spec) => ({
+ description: spec.description,
+ name: spec.name,
+ priority: spec.priority,
}));
}
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index bbae4787a27..8cebbfb5751 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -36,13 +36,13 @@ import {
import { app as electronApp, BrowserWindow } from 'electron';
import { HETERO_AGENT_FILES_DIR, HETERO_AGENT_TRACING_DIR } from '@/const/heteroAgent';
+import { detectHeterogeneousCliCommand } from '@/modules/binaries';
import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';
import type {
HeterogeneousAgentBuildPlan,
HeterogeneousAgentImageAttachment,
} from '@/modules/heterogeneousAgent/types';
import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';
-import { detectHeterogeneousCliCommand } from '@/modules/toolDetectors';
import { createLogger } from '@/utils/logger';
import { ControllerModule, IpcMethod } from './index';
@@ -480,7 +480,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
const command = this.resolveSessionCommand(session);
const status =
command === defaultCommand
- ? await this.app.toolDetectorManager?.detect?.(defaultCommand, true)
+ ? await this.app.binaryManager?.detect?.(defaultCommand, true)
: await detectHeterogeneousCliCommand(
session.agentType === 'claude-code' ? 'claude-code' : 'codex',
command,
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index ad8cb50a9d1..95983cd8616 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -407,7 +407,7 @@ describe('HeterogeneousAgentCtr', () => {
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
- toolDetectorManager: { detect },
+ binaryManager: { detect },
} as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
@@ -427,7 +427,7 @@ describe('HeterogeneousAgentCtr', () => {
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
- toolDetectorManager: { detect },
+ binaryManager: { detect },
} as any);
const { sessionId } = await ctr.startSession({
agentType: 'claude-code',
@@ -465,7 +465,7 @@ describe('HeterogeneousAgentCtr', () => {
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
- toolDetectorManager: { detect },
+ binaryManager: { detect },
} as any);
const { sessionId } = await ctr.startSession({
agentType: 'claude-code',
@@ -492,7 +492,7 @@ describe('HeterogeneousAgentCtr', () => {
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
- toolDetectorManager: { detect },
+ binaryManager: { detect },
} as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
@@ -518,7 +518,7 @@ describe('HeterogeneousAgentCtr', () => {
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
- toolDetectorManager: { detect },
+ binaryManager: { detect },
} as any);
const { sessionId } = await ctr.startSession({ agentType: 'codex', command: 'codex' });
await ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId });
@@ -549,7 +549,7 @@ describe('HeterogeneousAgentCtr', () => {
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
- toolDetectorManager: { detect },
+ binaryManager: { detect },
} as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index 25fc770f741..b7a66103ec5 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -108,7 +108,7 @@ const mockApp = {
return mockSearchService;
}),
localFileProtocolManager: mockLocalFileProtocolManager,
- toolDetectorManager: {
+ binaryManager: {
getBestTool: vi.fn(() => null), // No external tools available, use Node.js fallback
},
} as unknown as App;
diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.ts
index 8c4428a09d5..b6df34a1a66 100644
--- a/apps/desktop/src/main/controllers/registry.ts
+++ b/apps/desktop/src/main/controllers/registry.ts
@@ -1,6 +1,7 @@
import type { CreateServicesResult, IpcServiceConstructor, MergeIpcService } from '@/utils/ipc';
import AuthCtr from './AuthCtr';
+import BinaryCtr from './BinaryCtr';
import BrowserWindowsCtr from './BrowserWindowsCtr';
import CliCtr from './CliCtr';
import DevtoolsCtr from './DevtoolsCtr';
@@ -21,7 +22,6 @@ import ScreenCaptureCtr from './ScreenCaptureCtr';
import ShellCommandCtr from './ShellCommandCtr';
import ShortcutController from './ShortcutCtr';
import SystemController from './SystemCtr';
-import ToolDetectorCtr from './ToolDetectorCtr';
import TrayMenuCtr from './TrayMenuCtr';
import UpdaterCtr from './UpdaterCtr';
import WorkspaceCtr from './WorkspaceCtr';
@@ -48,7 +48,7 @@ export const controllerIpcConstructors = [
ShellCommandCtr,
ShortcutController,
SystemController,
- ToolDetectorCtr,
+ BinaryCtr,
TrayMenuCtr,
UpdaterCtr,
WorkspaceCtr,
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index 919a1c8d998..53247d07a08 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -12,23 +12,24 @@ import { binDir, buildDir } from '@/const/dir';
import { isDev } from '@/const/env';
import type { IControlModule } from '@/controllers';
import AuthCtr from '@/controllers/AuthCtr';
+import {
+ astSearchBinaries,
+ type BinaryCategory,
+ type BinarySpec,
+ browserAutomationBinaries,
+ cliAgentBinaries,
+ contentSearchBinaries,
+ fileSearchBinaries,
+ runtimeEnvironmentBinaries,
+} from '@/modules/binaries';
import { generateCliWrapper, getCliWrapperDir } from '@/modules/cliEmbedding';
import { ScreenCaptureManager } from '@/modules/screenCapture/ScreenCaptureManager';
-import {
- astSearchDetectors,
- browserAutomationDetectors,
- cliAgentDetectors,
- contentSearchDetectors,
- fileSearchDetectors,
- type IToolDetector,
- runtimeEnvironmentDetectors,
- type ToolCategory,
-} from '@/modules/toolDetectors';
import type { IServiceModule } from '@/services';
import { createLogger } from '@/utils/logger';
import { BrowserManager } from './browser/BrowserManager';
import { backendProxyProtocolManager } from './infrastructure/BackendProxyProtocolManager';
+import { BinaryManager } from './infrastructure/BinaryManager';
import { I18nManager } from './infrastructure/I18nManager';
import { IoCContainer } from './infrastructure/IoCContainer';
import { LocalFileProtocolManager } from './infrastructure/LocalFileProtocolManager';
@@ -36,7 +37,6 @@ import { ProtocolManager } from './infrastructure/ProtocolManager';
import { RendererUrlManager } from './infrastructure/RendererUrlManager';
import { StaticFileServerManager } from './infrastructure/StaticFileServerManager';
import { StoreManager } from './infrastructure/StoreManager';
-import { ToolDetectorManager } from './infrastructure/ToolDetectorManager';
import { UpdaterManager } from './infrastructure/UpdaterManager';
import { MenuManager } from './ui/MenuManager';
import { ShortcutManager } from './ui/ShortcutManager';
@@ -64,7 +64,7 @@ export class App {
protocolManager: ProtocolManager;
rendererUrlManager: RendererUrlManager;
localFileProtocolManager: LocalFileProtocolManager;
- toolDetectorManager: ToolDetectorManager;
+ binaryManager: BinaryManager;
screenCaptureManager: ScreenCaptureManager;
chromeFlags: string[] = ['OverlayScrollbar', 'FluentOverlayScrollbar', 'FluentScrollbar'];
@@ -91,13 +91,15 @@ export class App {
logger.info(` RAM: ${Math.round(os.totalmem() / 1024 / 1024 / 1024)} GB`);
logger.info(`PATH: ${app.getAppPath()}`);
logger.info(` lng: ${app.getLocale()}`);
- logger.info(` bin: ${binDir}`);
+ logger.info(` res: ${binDir}`);
logger.info('----------------------------------------------');
logger.info('Starting LobeHub...');
- // Append bundled binaries and CLI wrapper directories to PATH for tool resolution
+ // Append the CLI wrapper directory to PATH so spawned shells can resolve
+ // `lobehub` / `lh` / `lobe`. Managed binary dirs (e.g. agent-browser) are
+ // augmented separately by `binaryManager.augmentPath()` during bootstrap.
const pathSep = process.platform === 'win32' ? ';' : ':';
- process.env.PATH = `${process.env.PATH}${pathSep}${binDir}${pathSep}${getCliWrapperDir()}`;
+ process.env.PATH = `${process.env.PATH}${pathSep}${getCliWrapperDir()}`;
logger.debug('Initializing App');
// Initialize store manager
@@ -145,11 +147,11 @@ export class App {
this.trayManager = new TrayManager(this);
this.staticFileServerManager = new StaticFileServerManager(this);
this.protocolManager = new ProtocolManager(this);
- this.toolDetectorManager = new ToolDetectorManager(this);
+ this.binaryManager = new BinaryManager(this);
this.screenCaptureManager = new ScreenCaptureManager(this);
- // Register built-in tool detectors
- this.registerBuiltinToolDetectors();
+ // Register built-in binary specs
+ this.registerBuiltinBinarySpecs();
// Configure renderer loading strategy (dev server vs static export)
// should register before app ready
@@ -194,31 +196,29 @@ export class App {
}
/**
- * Register built-in tool detectors for content search and file search
+ * Register built-in binary specs the BinaryManager knows about.
*/
- private registerBuiltinToolDetectors() {
- logger.debug('Registering built-in tool detectors');
-
- const detectorCategories: Partial<Record<ToolCategory, IToolDetector[]>> = {
- 'runtime-environment': runtimeEnvironmentDetectors,
- 'cli-agents': cliAgentDetectors,
- 'ast-search': astSearchDetectors,
- 'browser-automation': browserAutomationDetectors,
- 'content-search': contentSearchDetectors,
- 'file-search': fileSearchDetectors,
+ private registerBuiltinBinarySpecs() {
+ logger.debug('Registering built-in binary specs');
+
+ const binaryCategories: Partial<Record<BinaryCategory, BinarySpec[]>> = {
+ 'runtime-environment': runtimeEnvironmentBinaries,
+ 'cli-agents': cliAgentBinaries,
+ 'ast-search': astSearchBinaries,
+ 'browser-automation': browserAutomationBinaries,
+ 'content-search': contentSearchBinaries,
+ 'file-search': fileSearchBinaries,
};
- for (const [category, detectors] of Object.entries(detectorCategories)) {
- if (detectors) {
- for (const detector of detectors) {
- this.toolDetectorManager.register(detector, category as ToolCategory);
+ for (const [category, specs] of Object.entries(binaryCategories)) {
+ if (specs) {
+ for (const spec of specs) {
+ this.binaryManager.register(spec, category as BinaryCategory);
}
}
}
- logger.info(
- `Registered ${this.toolDetectorManager.getRegisteredTools().length} tool detectors`,
- );
+ logger.info(`Registered ${this.binaryManager.getRegistered().length} binary specs`);
}
bootstrap = async () => {
@@ -244,6 +244,20 @@ export class App {
logger.warn('Failed to generate CLI wrapper:', error);
});
+ // Surface previously-installed managed binaries on PATH so spawned shells
+ // (and child agents) can resolve them without going through the manager.
+ this.binaryManager.augmentPath().catch((error) => {
+ logger.warn('Failed to augment PATH with managed binaries:', error);
+ });
+
+ // Lazy-install agent-browser in the background β€” keeps the installer
+ // light (no bundled binary) while still making the CLI available shortly
+ // after first launch. Errors are non-fatal; the Settings panel exposes a
+ // manual retry via `binaryService.detect / ensure` later.
+ this.binaryManager.ensure('agent-browser').catch((error) => {
+ logger.warn('[agent-browser] background ensure failed:', error);
+ });
+
// Initialize i18n. Note: app.getLocale() must be called after app.whenReady() to get the correct value
await this.i18n.init();
this.menuManager.initialize();
diff --git a/apps/desktop/src/main/core/infrastructure/BinaryManager.ts b/apps/desktop/src/main/core/infrastructure/BinaryManager.ts
new file mode 100644
index 00000000000..b377ef872cf
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/BinaryManager.ts
@@ -0,0 +1,816 @@
+import { exec, execFile, type ExecFileOptions, spawn } from 'node:child_process';
+import { createWriteStream } from 'node:fs';
+import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
+import https from 'node:https';
+import path from 'node:path';
+import { pipeline } from 'node:stream/promises';
+import { promisify } from 'node:util';
+
+import { app } from 'electron';
+
+import type { App } from '@/core/App';
+import { createLogger } from '@/utils/logger';
+
+const execPromise = promisify(exec);
+const execFilePromise = promisify(execFile);
+const logger = createLogger('core:BinaryManager');
+
+/**
+ * Where on the host a binary resolution came from. Lets the UI tell the user
+ * that the system-wide install is in use, vs the version this app downloaded
+ * into its own cache.
+ */
+export type BinarySource = 'system' | 'managed';
+
+/**
+ * Status of a registered binary on the host.
+ */
+export interface BinaryStatus {
+ available: boolean;
+ error?: string;
+ lastChecked?: Date;
+ /**
+ * Whether the spec opts into the manager's install/upgrade lifecycle. The UI
+ * uses this to know when to surface an Install / Update button next to an
+ * unavailable binary.
+ */
+ manageable?: boolean;
+ path?: string;
+ /**
+ * PATH value used to resolve/validate the command, surfaced only when it
+ * differs from the detector process's `process.env.PATH` (e.g. resolution
+ * fell back to the login-shell PATH). A caller that spawns the resolved
+ * `path` must carry this into the child's PATH, or a `#!/usr/bin/env node`
+ * shim that resolved here still fails with `env: node: No such file or
+ * directory` under the leaner inherited env.
+ */
+ resolvedPathEnv?: string;
+ /** Where the resolved binary lives β€” system PATH or the manager's cache. */
+ source?: BinarySource;
+ version?: string;
+}
+
+/**
+ * Context passed to `BinaryManageSpec.release` when computing a download URL.
+ */
+export interface BinaryReleaseContext {
+ arch: NodeJS.Architecture;
+ platform: NodeJS.Platform;
+ version: string;
+}
+
+/**
+ * Optional install/upgrade lifecycle for a binary. When present, the manager
+ * can lazily download the binary into `userData/bin/<name>/<version>/` on
+ * first use, strip macOS quarantine, and run post-install steps.
+ */
+export interface BinaryManageSpec {
+ /**
+ * Optional override to fetch the latest version string (e.g. via GitHub
+ * releases API). Defaults to GitHub `releases/latest` when `githubRepo`
+ * is set, otherwise the manager requires `pinnedVersion`.
+ */
+ fetchLatestVersion?: () => Promise<string>;
+ /**
+ * GitHub `owner/repo` slug β€” used by the default `fetchLatestVersion` and
+ * surfaced in logs for diagnostics.
+ */
+ githubRepo?: string;
+ /**
+ * macOS Gatekeeper quarantine handling for the downloaded binary.
+ * - `strip` (default): remove `com.apple.quarantine` xattr.
+ * - `none`: leave the binary alone.
+ */
+ macosQuarantine?: 'strip' | 'none';
+ /** Pinned version, used when `fetchLatestVersion` is not provided. */
+ pinnedVersion?: string;
+ /**
+ * Commands to run against the freshly installed binary, e.g. `['install']`
+ * so `agent-browser install` pulls Chrome on first set-up. Each entry is
+ * an `argv` array passed to `execFile(<installedPath>, args)`.
+ */
+ postInstall?: string[][];
+ /**
+ * Build the release artifact URL for `(version, platform, arch)`. The
+ * returned URL must end in a downloadable file β€” redirects are followed.
+ */
+ release: (ctx: BinaryReleaseContext) => string;
+}
+
+/**
+ * Specification for a binary the desktop app knows about β€” modules implement
+ * this to register detection (and optional install/upgrade) logic.
+ */
+export interface BinarySpec {
+ /** Human-readable description */
+ description?: string;
+ /** Detection method */
+ detect: () => Promise<BinaryStatus>;
+ /** Optional install/upgrade lifecycle */
+ manage?: BinaryManageSpec;
+ /** Binary name, e.g., 'rg', 'mdfind', 'agent-browser' */
+ name: string;
+ /** Priority within category, lower number = higher priority */
+ priority?: number;
+}
+
+/**
+ * Binary categories
+ */
+export type BinaryCategory =
+ | 'content-search'
+ | 'ast-search'
+ | 'file-search'
+ | 'browser-automation'
+ | 'runtime-environment'
+ | 'cli-agents'
+ | 'system'
+ | 'custom';
+
+/**
+ * Binary Manager
+ *
+ * A plugin-style manager for binaries the desktop app cares about β€” handles
+ * detection plus an optional install / upgrade lifecycle for binaries the
+ * app ships with. Modules register their own specs and query status.
+ *
+ * @example
+ * ```typescript
+ * manager.register({
+ * name: 'agent-browser',
+ * detect: ...,
+ * manage: {
+ * pinnedVersion: '0.31.1',
+ * release: ({ version, platform, arch }) =>
+ * `https://github.com/vercel-labs/agent-browser/releases/download/v${version}/agent-browser-${platform}-${arch}`,
+ * postInstall: [['install']],
+ * },
+ * }, 'browser-automation');
+ *
+ * const binPath = await manager.ensure('agent-browser'); // downloads if missing
+ * ```
+ */
+export class BinaryManager {
+ private app: App;
+ private specs = new Map<string, BinarySpec>();
+ private statusCache = new Map<string, BinaryStatus>();
+ private categoryMap = new Map<BinaryCategory, Set<string>>();
+ /** De-dupe concurrent ensure() / install() calls per binary name. */
+ private inFlight = new Map<string, Promise<string>>();
+ private _cacheRoot: string | undefined;
+
+ constructor(app: App) {
+ logger.debug('Initializing BinaryManager');
+ this.app = app;
+ }
+
+ /**
+ * Resolve the per-user binary cache root lazily β€” `app.getPath('userData')`
+ * isn't usable at import time, only after the Electron app is initialized.
+ */
+ private get cacheRoot(): string {
+ if (!this._cacheRoot) {
+ this._cacheRoot = path.join(app.getPath('userData'), 'bin');
+ }
+ return this._cacheRoot;
+ }
+
+ /**
+ * Register a binary spec
+ * @param spec The spec to register
+ * @param category Binary category for grouping
+ */
+ register(spec: BinarySpec, category: BinaryCategory = 'custom'): void {
+ const { name } = spec;
+
+ if (this.specs.has(name)) {
+ logger.warn(`Spec for '${name}' already registered, overwriting`);
+ }
+
+ this.specs.set(name, spec);
+
+ if (!this.categoryMap.has(category)) {
+ this.categoryMap.set(category, new Set());
+ }
+ this.categoryMap.get(category)!.add(name);
+
+ logger.debug(
+ `Registered spec: ${name} (category: ${category}, priority: ${spec.priority ?? 'default'}, manageable: ${Boolean(spec.manage)})`,
+ );
+ }
+
+ /**
+ * Unregister a binary spec
+ * @param name Binary name to unregister
+ */
+ unregister(name: string): boolean {
+ if (!this.specs.has(name)) {
+ return false;
+ }
+
+ this.specs.delete(name);
+ this.statusCache.delete(name);
+
+ for (const names of this.categoryMap.values()) {
+ names.delete(name);
+ }
+
+ logger.debug(`Unregistered spec: ${name}`);
+ return true;
+ }
+
+ /**
+ * Detect a single binary. Checks the manager's own cache first so a
+ * previously-installed managed copy wins over a stale `which` result.
+ * @param name Binary name
+ * @param force Force detection, bypass cache
+ */
+ async detect(name: string, force = false): Promise<BinaryStatus> {
+ const spec = this.specs.get(name);
+ if (!spec) {
+ return {
+ available: false,
+ error: `No spec registered for '${name}'`,
+ };
+ }
+
+ if (!force && this.statusCache.has(name)) {
+ return this.statusCache.get(name)!;
+ }
+
+ const manageable = Boolean(spec.manage);
+
+ // Managed install wins: if we previously downloaded a copy, surface it
+ // directly. Avoids the cycle of installing-then-detect-not-seeing-it.
+ const managedPath = await this.findManagedPath(name);
+ if (managedPath) {
+ const version = await this.readInstalledVersion(name);
+ const status: BinaryStatus = {
+ available: true,
+ lastChecked: new Date(),
+ manageable,
+ path: managedPath,
+ source: 'managed',
+ version: version ?? undefined,
+ };
+ this.statusCache.set(name, status);
+ return status;
+ }
+
+ try {
+ logger.debug(`Detecting binary: ${name}`);
+ const detected = await spec.detect();
+ const status: BinaryStatus = {
+ ...detected,
+ lastChecked: new Date(),
+ manageable,
+ source: detected.available ? 'system' : undefined,
+ };
+ this.statusCache.set(name, status);
+
+ logger.debug(`Binary ${name} detection result:`, {
+ available: status.available,
+ path: status.path,
+ source: status.source,
+ version: status.version,
+ });
+
+ return status;
+ } catch (error) {
+ const status: BinaryStatus = {
+ available: false,
+ error: (error as Error).message,
+ lastChecked: new Date(),
+ manageable,
+ };
+ this.statusCache.set(name, status);
+ logger.error(`Error detecting binary ${name}:`, error);
+ return status;
+ }
+ }
+
+ /**
+ * Detect all registered binaries
+ * @param force Force detection, bypass cache
+ */
+ async detectAll(force = false): Promise<Map<string, BinaryStatus>> {
+ const results = new Map<string, BinaryStatus>();
+
+ await Promise.all(
+ Array.from(this.specs.keys()).map(async (name) => {
+ const status = await this.detect(name, force);
+ results.set(name, status);
+ }),
+ );
+
+ return results;
+ }
+
+ /**
+ * Detect all binaries in a category
+ * @param category Binary category
+ * @param force Force detection, bypass cache
+ */
+ async detectCategory(
+ category: BinaryCategory,
+ force = false,
+ ): Promise<Map<string, BinaryStatus>> {
+ const names = this.categoryMap.get(category);
+ if (!names) {
+ return new Map();
+ }
+
+ const results = new Map<string, BinaryStatus>();
+
+ await Promise.all(
+ Array.from(names).map(async (name) => {
+ const status = await this.detect(name, force);
+ results.set(name, status);
+ }),
+ );
+
+ return results;
+ }
+
+ /**
+ * Get cached status for a binary
+ * @param name Binary name
+ */
+ getStatus(name: string): BinaryStatus | undefined {
+ return this.statusCache.get(name);
+ }
+
+ /**
+ * Get all cached statuses
+ */
+ getAllStatus(): Map<string, BinaryStatus> {
+ return new Map(this.statusCache);
+ }
+
+ /**
+ * Get the best available binary in a category. Method name kept verbatim
+ * so it satisfies the `ToolDetector` contract in `@lobechat/local-file-shell`
+ * (which the content/file search impls inject).
+ * @param category Binary category
+ */
+ async getBestTool(category: BinaryCategory): Promise<string | null> {
+ const names = this.categoryMap.get(category);
+ if (!names || names.size === 0) {
+ return null;
+ }
+
+ const sortedSpecs = Array.from(names)
+ .map((name) => this.specs.get(name)!)
+ .filter(Boolean)
+ .sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));
+
+ for (const spec of sortedSpecs) {
+ const status = await this.detect(spec.name);
+ if (status.available) {
+ return spec.name;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Get all binaries in a category, sorted by priority
+ * @param category Binary category
+ */
+ getInCategory(category: BinaryCategory): BinarySpec[] {
+ const names = this.categoryMap.get(category);
+ if (!names) {
+ return [];
+ }
+
+ return Array.from(names)
+ .map((name) => this.specs.get(name)!)
+ .filter(Boolean)
+ .sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));
+ }
+
+ /**
+ * Clear status cache
+ * @param name Optional binary name; if not provided, clears all
+ */
+ clearCache(name?: string): void {
+ if (name) {
+ this.statusCache.delete(name);
+ logger.debug(`Cleared cache for: ${name}`);
+ } else {
+ this.statusCache.clear();
+ logger.debug('Cleared all cache');
+ }
+ }
+
+ /**
+ * Get all registered binary names
+ */
+ getRegistered(): string[] {
+ return Array.from(this.specs.keys());
+ }
+
+ /**
+ * Get all categories
+ */
+ getCategories(): BinaryCategory[] {
+ return Array.from(this.categoryMap.keys());
+ }
+
+ /**
+ * Check if a binary is registered
+ */
+ isRegistered(name: string): boolean {
+ return this.specs.has(name);
+ }
+
+ // ====================================================================
+ // PATH integration
+ // ====================================================================
+
+ /**
+ * Walk over registered specs and append each currently-installed managed
+ * binary's directory to `process.env.PATH`. Idempotent β€” a directory is
+ * never appended twice. Call once at bootstrap so shells spawned by child
+ * agents can resolve managed binaries without going through the manager.
+ */
+ async augmentPath(): Promise<void> {
+ for (const name of this.specs.keys()) {
+ const managedPath = await this.findManagedPath(name);
+ if (managedPath) {
+ this.appendToPath(path.dirname(managedPath));
+ }
+ }
+ }
+
+ /** Append `dir` to PATH if not already present. */
+ private appendToPath(dir: string): void {
+ const sep = process.platform === 'win32' ? ';' : ':';
+ const current = process.env.PATH ?? '';
+ const parts = current.split(sep);
+ if (parts.includes(dir)) return;
+ process.env.PATH = current ? `${current}${sep}${dir}` : dir;
+ logger.debug(`Appended to PATH: ${dir}`);
+ }
+
+ // ====================================================================
+ // Lifecycle: install / upgrade / ensure
+ // ====================================================================
+
+ /**
+ * Ensure a binary is available, downloading the managed copy on demand if
+ * the host doesn't already have it. Returns the absolute executable path.
+ * Throws when the binary is unmanageable AND not on the system PATH.
+ *
+ * Concurrent calls for the same name share a single in-flight install.
+ */
+ async ensure(name: string): Promise<string> {
+ const inflight = this.inFlight.get(name);
+ if (inflight) return inflight;
+
+ const task = this._ensure(name).finally(() => {
+ this.inFlight.delete(name);
+ });
+ this.inFlight.set(name, task);
+ return task;
+ }
+
+ private async _ensure(name: string): Promise<string> {
+ const spec = this.specs.get(name);
+ if (!spec) throw new Error(`BinaryManager: no spec registered for '${name}'`);
+
+ // Existing managed install wins β€” keeps a previously-downloaded copy
+ // from being re-detected as "system" via PATH lookup.
+ const managedPath = await this.findManagedPath(name);
+ if (managedPath) return managedPath;
+
+ // System install on PATH satisfies the request without managed install.
+ const status = await this.detect(name, true);
+ if (status.available && status.path) return status.path;
+
+ if (!spec.manage) {
+ throw new Error(
+ `Binary '${name}' is not available on the system PATH and does not opt into management. ` +
+ `Install it manually or extend its BinarySpec with a 'manage' block.`,
+ );
+ }
+
+ return this.install(name);
+ }
+
+ /**
+ * Download (or re-download) the managed copy of a binary. When `version`
+ * is omitted the spec's pinnedVersion is used, falling back to the latest
+ * release. Use this directly to force an upgrade.
+ */
+ async install(name: string, version?: string): Promise<string> {
+ const spec = this.specs.get(name);
+ if (!spec?.manage) {
+ throw new Error(`Binary '${name}' is not manageable`);
+ }
+ const manageSpec = spec.manage;
+
+ const resolvedVersion =
+ version ?? manageSpec.pinnedVersion ?? (await this.fetchLatestVersion(name));
+ if (!resolvedVersion) {
+ throw new Error(
+ `Cannot resolve version for '${name}' β€” set 'pinnedVersion' or 'githubRepo' / 'fetchLatestVersion' on its manage spec.`,
+ );
+ }
+
+ const releaseUrl = manageSpec.release({
+ arch: process.arch,
+ platform: process.platform,
+ version: resolvedVersion,
+ });
+
+ const installDir = path.join(this.cacheRoot, name, resolvedVersion);
+ const fileName = process.platform === 'win32' ? `${name}.exe` : name;
+ const targetPath = path.join(installDir, fileName);
+
+ await mkdir(installDir, { recursive: true });
+
+ logger.info(`[${name}] downloading v${resolvedVersion} from ${releaseUrl}`);
+ await downloadWithRedirects(releaseUrl, targetPath);
+
+ const { size } = await stat(targetPath);
+ logger.info(`[${name}] downloaded ${(size / 1024 / 1024).toFixed(1)} MB β†’ ${targetPath}`);
+
+ if (process.platform !== 'win32') {
+ await chmod(targetPath, 0o755);
+ }
+
+ if (process.platform === 'darwin' && (manageSpec.macosQuarantine ?? 'strip') === 'strip') {
+ await stripMacosQuarantine(targetPath);
+ }
+
+ // Atomically point the .installed marker at the new version so concurrent
+ // readers either see the old or new version, never an empty file.
+ const markerPath = this.installedMarkerPath(name);
+ const tmpMarker = `${markerPath}.${process.pid}.tmp`;
+ await writeFile(tmpMarker, resolvedVersion, 'utf8');
+ await rm(markerPath, { force: true });
+ await writeFile(markerPath, resolvedVersion, 'utf8');
+ await rm(tmpMarker, { force: true });
+
+ if (manageSpec.postInstall?.length) {
+ for (const args of manageSpec.postInstall) {
+ logger.info(`[${name}] post-install: ${args.join(' ')}`);
+ try {
+ await execFilePromise(targetPath, args, { timeout: 10 * 60 * 1000 } as ExecFileOptions);
+ } catch (error) {
+ logger.warn(`[${name}] post-install step failed:`, error);
+ }
+ }
+ }
+
+ // Invalidate the cached status so the next detect() reflects the new install.
+ this.statusCache.delete(name);
+
+ // Make the freshly installed binary immediately resolvable from PATH so
+ // child processes spawned right after ensure() succeed without restart.
+ this.appendToPath(installDir);
+
+ return targetPath;
+ }
+
+ /**
+ * Upgrade a managed binary to a specific version, or to the latest if
+ * `version` is omitted. Returns the new installed path.
+ */
+ async upgrade(name: string, version?: string): Promise<string> {
+ const spec = this.specs.get(name);
+ if (!spec?.manage) throw new Error(`Binary '${name}' is not manageable`);
+
+ const target =
+ version ??
+ (spec.manage.fetchLatestVersion || spec.manage.githubRepo
+ ? await this.fetchLatestVersion(name)
+ : undefined);
+
+ if (!target) {
+ throw new Error(
+ `Cannot resolve upgrade version for '${name}' β€” pass a version or set 'githubRepo' / 'fetchLatestVersion'.`,
+ );
+ }
+
+ const current = await this.readInstalledVersion(name);
+ if (current === target) {
+ logger.info(`[${name}] already at v${target}, skipping upgrade`);
+ const existing = await this.findManagedPath(name);
+ if (existing) return existing;
+ }
+
+ return this.install(name, target);
+ }
+
+ /**
+ * Path to the currently-installed managed copy of `name`, or `null` if no
+ * install marker exists or the marker points at a missing file.
+ */
+ async findManagedPath(name: string): Promise<string | null> {
+ const version = await this.readInstalledVersion(name);
+ if (!version) return null;
+ const fileName = process.platform === 'win32' ? `${name}.exe` : name;
+ const candidate = path.join(this.cacheRoot, name, version, fileName);
+ try {
+ await stat(candidate);
+ return candidate;
+ } catch {
+ return null;
+ }
+ }
+
+ /**
+ * Currently-installed version recorded for `name`, or `null` if none.
+ */
+ async readInstalledVersion(name: string): Promise<string | null> {
+ try {
+ const raw = await readFile(this.installedMarkerPath(name), 'utf8');
+ const trimmed = raw.trim();
+ return trimmed || null;
+ } catch {
+ return null;
+ }
+ }
+
+ private installedMarkerPath(name: string): string {
+ return path.join(this.cacheRoot, name, '.installed');
+ }
+
+ private async fetchLatestVersion(name: string): Promise<string> {
+ const spec = this.specs.get(name);
+ if (!spec?.manage) throw new Error(`Binary '${name}' is not manageable`);
+
+ if (spec.manage.fetchLatestVersion) {
+ return spec.manage.fetchLatestVersion();
+ }
+
+ if (!spec.manage.githubRepo) {
+ throw new Error(
+ `Cannot fetch latest version for '${name}' β€” set 'githubRepo' or 'fetchLatestVersion' on its manage spec.`,
+ );
+ }
+
+ const tag = await fetchGithubLatestTag(spec.manage.githubRepo);
+ return tag.replace(/^v/, '');
+ }
+}
+
+// ========================================
+// Helper: define a command-based binary spec
+// ========================================
+
+/**
+ * Define a simple command-based binary spec β€” detects via `which`/`where`
+ * and optionally reads `--version`. Useful for tools that follow the standard
+ * "on PATH or not" pattern.
+ */
+export function defineCommandBinary(
+ name: string,
+ options: {
+ description?: string;
+ manage?: BinaryManageSpec;
+ priority?: number;
+ versionFlag?: string;
+ whichCommand?: string;
+ } = {},
+): BinarySpec {
+ const { description, manage, priority, versionFlag = '--version', whichCommand } = options;
+
+ return {
+ description,
+ async detect(): Promise<BinaryStatus> {
+ try {
+ const whichCmd = whichCommand || (process.platform === 'win32' ? 'where' : 'which');
+ const { stdout: pathOut } = await execPromise(`${whichCmd} ${name}`, { timeout: 3000 });
+ const toolPath = pathOut.trim().split('\n')[0];
+
+ let version: string | undefined;
+ try {
+ const { stdout: versionOut } = await execPromise(`${name} ${versionFlag}`, {
+ timeout: 3000,
+ });
+ version = versionOut.trim().split('\n')[0];
+ } catch {
+ // Some binaries don't support a version flag
+ }
+
+ return {
+ available: true,
+ path: toolPath,
+ version,
+ };
+ } catch {
+ return {
+ available: false,
+ };
+ }
+ },
+ manage,
+ name,
+ priority,
+ };
+}
+
+// ========================================
+// Internal helpers β€” download + Gatekeeper handling
+// ========================================
+
+/**
+ * Follow HTTP(S) redirects and stream the body to `dest`. Mirrors the older
+ * `scripts/download-agent-browser.mjs` semantics β€” 5 hops max, errors on
+ * non-2xx, no checksum verification (left to the spec when needed).
+ */
+async function downloadWithRedirects(url: string, dest: string, maxRedirects = 5): Promise<void> {
+ if (maxRedirects <= 0) throw new Error('Too many redirects while downloading binary');
+
+ await new Promise<void>((resolve, reject) => {
+ https
+ .get(url, { headers: { 'User-Agent': 'lobehub-desktop-binary-manager' } }, (res) => {
+ if (
+ res.statusCode &&
+ res.statusCode >= 300 &&
+ res.statusCode < 400 &&
+ res.headers.location
+ ) {
+ const next = res.headers.location;
+ res.resume();
+ downloadWithRedirects(next, dest, maxRedirects - 1).then(resolve, reject);
+ return;
+ }
+
+ if (res.statusCode !== 200) {
+ res.resume();
+ reject(new Error(`Download failed: HTTP ${res.statusCode} from ${url}`));
+ return;
+ }
+
+ const file = createWriteStream(dest);
+ pipeline(res, file).then(resolve, reject);
+ })
+ .on('error', reject);
+ });
+}
+
+/**
+ * Strip the `com.apple.quarantine` xattr from a freshly downloaded binary on
+ * macOS so Gatekeeper doesn't refuse to exec ad-hoc signed artifacts. No-op
+ * (silent) on every other platform, or when no quarantine attribute exists.
+ */
+async function stripMacosQuarantine(filePath: string): Promise<void> {
+ await new Promise<void>((resolve) => {
+ const child = spawn('xattr', ['-d', 'com.apple.quarantine', filePath], {
+ stdio: 'ignore',
+ });
+ child.on('error', () => resolve());
+ child.on('exit', () => resolve());
+ });
+}
+
+/**
+ * Look up the most recent release tag for `owner/repo`. Uses the unauthenticated
+ * GitHub API; intended for occasional version-check calls, not hot loops.
+ */
+async function fetchGithubLatestTag(repo: string): Promise<string> {
+ const apiUrl = `https://api.github.com/repos/${repo}/releases/latest`;
+ return new Promise<string>((resolve, reject) => {
+ https
+ .get(
+ apiUrl,
+ {
+ headers: {
+ 'Accept': 'application/vnd.github+json',
+ 'User-Agent': 'lobehub-desktop-binary-manager',
+ },
+ },
+ (res) => {
+ if (res.statusCode !== 200) {
+ res.resume();
+ reject(new Error(`GitHub release lookup failed for ${repo}: HTTP ${res.statusCode}`));
+ return;
+ }
+
+ const chunks: Buffer[] = [];
+ res.on('data', (chunk: Buffer) => chunks.push(chunk));
+ res.on('end', () => {
+ try {
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as {
+ tag_name?: string;
+ };
+ if (!body.tag_name) {
+ reject(new Error(`GitHub release lookup for ${repo} returned no tag_name`));
+ return;
+ }
+ resolve(body.tag_name);
+ } catch (error) {
+ reject(error as Error);
+ }
+ });
+ res.on('error', reject);
+ },
+ )
+ .on('error', reject);
+ });
+}
diff --git a/apps/desktop/src/main/core/infrastructure/ToolDetectorManager.ts b/apps/desktop/src/main/core/infrastructure/ToolDetectorManager.ts
deleted file mode 100644
index c92f117dff2..00000000000
--- a/apps/desktop/src/main/core/infrastructure/ToolDetectorManager.ts
+++ /dev/null
@@ -1,368 +0,0 @@
-import { exec } from 'node:child_process';
-import { promisify } from 'node:util';
-
-import type { App } from '@/core/App';
-import { createLogger } from '@/utils/logger';
-
-const execPromise = promisify(exec);
-const logger = createLogger('core:ToolDetectorManager');
-
-/**
- * Tool detection status
- */
-export interface ToolStatus {
- available: boolean;
- error?: string;
- lastChecked?: Date;
- path?: string;
- /**
- * PATH value used to resolve/validate the command, surfaced only when it
- * differs from the detector process's `process.env.PATH` (e.g. resolution
- * fell back to the login-shell PATH). A caller that spawns the resolved
- * `path` must carry this into the child's PATH, or a `#!/usr/bin/env node`
- * shim that resolved here still fails with `env: node: No such file or
- * directory` under the leaner inherited env.
- */
- resolvedPathEnv?: string;
- version?: string;
-}
-
-/**
- * Tool detector interface - modules implement this to register detection logic
- */
-export interface IToolDetector {
- /** Description */
- description?: string;
- /** Detection method */
- detect: () => Promise<ToolStatus>;
- /** Tool name, e.g., 'rg', 'mdfind' */
- name: string;
- /** Priority within category, lower number = higher priority */
- priority?: number;
-}
-
-/**
- * Tool categories
- */
-export type ToolCategory =
- | 'content-search'
- | 'ast-search'
- | 'file-search'
- | 'browser-automation'
- | 'runtime-environment'
- | 'cli-agents'
- | 'system'
- | 'custom';
-
-/**
- * Tool Detector Manager
- *
- * A plugin-style manager for detecting system tools availability.
- * Modules can register their own detectors and query tool status.
- *
- * @example
- * ```typescript
- * // Register a detector
- * manager.register({
- * name: 'rg',
- * description: 'ripgrep',
- * priority: 1,
- * async detect() { ... }
- * }, 'content-search');
- *
- * // Query status
- * const status = await manager.detect('rg');
- * const bestTool = await manager.getBestTool('content-search');
- * ```
- */
-export class ToolDetectorManager {
- private app: App;
- private detectors = new Map<string, IToolDetector>();
- private statusCache = new Map<string, ToolStatus>();
- private categoryMap = new Map<ToolCategory, Set<string>>();
- private initialized = false;
-
- constructor(app: App) {
- logger.debug('Initializing ToolDetectorManager');
- this.app = app;
- }
-
- /**
- * Register a tool detector
- * @param detector The detector to register
- * @param category Tool category for grouping
- */
- register(detector: IToolDetector, category: ToolCategory = 'custom'): void {
- const { name } = detector;
-
- if (this.detectors.has(name)) {
- logger.warn(`Detector for '${name}' already registered, overwriting`);
- }
-
- this.detectors.set(name, detector);
-
- // Add to category
- if (!this.categoryMap.has(category)) {
- this.categoryMap.set(category, new Set());
- }
- this.categoryMap.get(category)!.add(name);
-
- logger.debug(
- `Registered detector: ${name} (category: ${category}, priority: ${detector.priority ?? 'default'})`,
- );
- }
-
- /**
- * Unregister a tool detector
- * @param name Tool name to unregister
- */
- unregister(name: string): boolean {
- if (!this.detectors.has(name)) {
- return false;
- }
-
- this.detectors.delete(name);
- this.statusCache.delete(name);
-
- // Remove from category
- for (const tools of this.categoryMap.values()) {
- tools.delete(name);
- }
-
- logger.debug(`Unregistered detector: ${name}`);
- return true;
- }
-
- /**
- * Detect a single tool
- * @param name Tool name
- * @param force Force detection, bypass cache
- */
- async detect(name: string, force = false): Promise<ToolStatus> {
- const detector = this.detectors.get(name);
- if (!detector) {
- return {
- available: false,
- error: `No detector registered for '${name}'`,
- };
- }
-
- // Return cached result if available and not forced
- if (!force && this.statusCache.has(name)) {
- return this.statusCache.get(name)!;
- }
-
- try {
- logger.debug(`Detecting tool: ${name}`);
- const status = await detector.detect();
- status.lastChecked = new Date();
- this.statusCache.set(name, status);
-
- logger.debug(`Tool ${name} detection result:`, {
- available: status.available,
- path: status.path,
- version: status.version,
- });
-
- return status;
- } catch (error) {
- const status: ToolStatus = {
- available: false,
- error: (error as Error).message,
- lastChecked: new Date(),
- };
- this.statusCache.set(name, status);
- logger.error(`Error detecting tool ${name}:`, error);
- return status;
- }
- }
-
- /**
- * Detect all registered tools
- * @param force Force detection, bypass cache
- */
- async detectAll(force = false): Promise<Map<string, ToolStatus>> {
- const results = new Map<string, ToolStatus>();
-
- await Promise.all(
- Array.from(this.detectors.keys()).map(async (name) => {
- const status = await this.detect(name, force);
- results.set(name, status);
- }),
- );
-
- return results;
- }
-
- /**
- * Detect all tools in a category
- * @param category Tool category
- * @param force Force detection, bypass cache
- */
- async detectCategory(category: ToolCategory, force = false): Promise<Map<string, ToolStatus>> {
- const tools = this.categoryMap.get(category);
- if (!tools) {
- return new Map();
- }
-
- const results = new Map<string, ToolStatus>();
-
- await Promise.all(
- Array.from(tools).map(async (name) => {
- const status = await this.detect(name, force);
- results.set(name, status);
- }),
- );
-
- return results;
- }
-
- /**
- * Get cached status for a tool
- * @param name Tool name
- */
- getStatus(name: string): ToolStatus | undefined {
- return this.statusCache.get(name);
- }
-
- /**
- * Get all cached statuses
- */
- getAllStatus(): Map<string, ToolStatus> {
- return new Map(this.statusCache);
- }
-
- /**
- * Get the best available tool in a category
- * Returns the first available tool sorted by priority
- * @param category Tool category
- */
- async getBestTool(category: ToolCategory): Promise<string | null> {
- const tools = this.categoryMap.get(category);
- if (!tools || tools.size === 0) {
- return null;
- }
-
- // Get detectors and sort by priority
- const sortedDetectors = Array.from(tools)
- .map((name) => this.detectors.get(name)!)
- .filter(Boolean)
- .sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));
-
- // Find first available tool
- for (const detector of sortedDetectors) {
- const status = await this.detect(detector.name);
- if (status.available) {
- return detector.name;
- }
- }
-
- return null;
- }
-
- /**
- * Get all tools in a category, sorted by priority
- * @param category Tool category
- */
- getToolsInCategory(category: ToolCategory): IToolDetector[] {
- const tools = this.categoryMap.get(category);
- if (!tools) {
- return [];
- }
-
- return Array.from(tools)
- .map((name) => this.detectors.get(name)!)
- .filter(Boolean)
- .sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));
- }
-
- /**
- * Clear status cache
- * @param name Optional tool name; if not provided, clears all
- */
- clearCache(name?: string): void {
- if (name) {
- this.statusCache.delete(name);
- logger.debug(`Cleared cache for: ${name}`);
- } else {
- this.statusCache.clear();
- logger.debug('Cleared all cache');
- }
- }
-
- /**
- * Get all registered tool names
- */
- getRegisteredTools(): string[] {
- return Array.from(this.detectors.keys());
- }
-
- /**
- * Get all categories
- */
- getCategories(): ToolCategory[] {
- return Array.from(this.categoryMap.keys());
- }
-
- /**
- * Check if a tool is registered
- */
- isRegistered(name: string): boolean {
- return this.detectors.has(name);
- }
-}
-
-// ========================================
-// Helper: Create a command-based detector
-// ========================================
-
-/**
- * Create a simple command-based detector
- * Useful for common tools that follow standard patterns
- */
-export function createCommandDetector(
- name: string,
- options: {
- description?: string;
- priority?: number;
- versionFlag?: string;
- whichCommand?: string;
- } = {},
-): IToolDetector {
- const { description, priority, versionFlag = '--version', whichCommand } = options;
-
- return {
- description,
- async detect(): Promise<ToolStatus> {
- try {
- // Check if tool exists
- const whichCmd = whichCommand || (process.platform === 'win32' ? 'where' : 'which');
- const { stdout: pathOut } = await execPromise(`${whichCmd} ${name}`, { timeout: 3000 });
- const toolPath = pathOut.trim().split('\n')[0];
-
- // Try to get version
- let version: string | undefined;
- try {
- const { stdout: versionOut } = await execPromise(`${name} ${versionFlag}`, {
- timeout: 3000,
- });
- version = versionOut.trim().split('\n')[0];
- } catch {
- // Some tools don't support version flag
- }
-
- return {
- available: true,
- path: toolPath,
- version,
- };
- } catch {
- return {
- available: false,
- };
- }
- },
- name,
- priority,
- };
-}
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts
new file mode 100644
index 00000000000..6609207aa29
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts
@@ -0,0 +1,329 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App as AppCore } from '../../App';
+import type { BinarySpec, BinaryStatus } from '../BinaryManager';
+
+const { mockUserDataDir, setUserDataDir } = vi.hoisted(() => {
+ const ref = { current: '' };
+ return {
+ mockUserDataDir: ref,
+ setUserDataDir: (dir: string) => {
+ ref.current = dir;
+ },
+ };
+});
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: (key: string) => {
+ if (key === 'userData') return mockUserDataDir.current;
+ throw new Error(`unexpected app.getPath('${key}') in test`);
+ },
+ },
+}));
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+}));
+
+// Import AFTER the mocks so the singleton logger and electron stub are wired.
+const { BinaryManager, defineCommandBinary } = await import('../BinaryManager');
+
+const stubApp = {} as AppCore;
+
+const writeInstalledMarker = async (
+ cacheRoot: string,
+ name: string,
+ version: string,
+ fileContent = 'fake-binary',
+) => {
+ const dir = path.join(cacheRoot, name, version);
+ await mkdir(dir, { recursive: true });
+ const fileName = process.platform === 'win32' ? `${name}.exe` : name;
+ await writeFile(path.join(dir, fileName), fileContent, 'utf8');
+ await writeFile(path.join(cacheRoot, name, '.installed'), version, 'utf8');
+ return path.join(dir, fileName);
+};
+
+let workspace: string;
+let cacheRoot: string;
+let originalPath: string | undefined;
+
+beforeEach(async () => {
+ workspace = await mkdtemp(path.join(tmpdir(), 'binmgr-'));
+ cacheRoot = path.join(workspace, 'bin');
+ setUserDataDir(workspace);
+ originalPath = process.env.PATH;
+});
+
+afterEach(async () => {
+ process.env.PATH = originalPath;
+ await rm(workspace, { force: true, recursive: true });
+});
+
+describe('BinaryManager', () => {
+ describe('register / getRegistered / isRegistered', () => {
+ it('records specs and categories, surfaces manageable flag', () => {
+ const mgr = new BinaryManager(stubApp);
+ const a: BinarySpec = {
+ detect: async () => ({ available: false }),
+ name: 'a',
+ };
+ const b: BinarySpec = {
+ detect: async () => ({ available: false }),
+ manage: { pinnedVersion: '1.0.0', release: () => 'https://example.com/b' },
+ name: 'b',
+ };
+ mgr.register(a, 'content-search');
+ mgr.register(b, 'browser-automation');
+
+ expect(mgr.getRegistered()).toEqual(['a', 'b']);
+ expect(mgr.isRegistered('a')).toBe(true);
+ expect(mgr.isRegistered('missing')).toBe(false);
+ expect(mgr.getCategories()).toEqual(['content-search', 'browser-automation']);
+ expect(mgr.getInCategory('browser-automation').map((s) => s.name)).toEqual(['b']);
+ });
+ });
+
+ describe('detect', () => {
+ it('caches detect() and stamps `source: system` for PATH-resolved binaries', async () => {
+ const mgr = new BinaryManager(stubApp);
+ const detect = vi.fn<() => Promise<BinaryStatus>>().mockResolvedValue({
+ available: true,
+ path: '/usr/local/bin/foo',
+ version: '1.0',
+ });
+ mgr.register({ detect, name: 'foo' }, 'content-search');
+
+ const first = await mgr.detect('foo');
+ const second = await mgr.detect('foo');
+
+ expect(first.source).toBe('system');
+ expect(first.manageable).toBe(false);
+ expect(detect).toHaveBeenCalledTimes(1);
+ expect(second).toBe(first);
+ });
+
+ it('prefers the managed cache over the spec detect() result', async () => {
+ const installedPath = await writeInstalledMarker(cacheRoot, 'foo', '2.3.4');
+ const mgr = new BinaryManager(stubApp);
+ const detect = vi.fn<() => Promise<BinaryStatus>>().mockResolvedValue({
+ available: true,
+ path: '/usr/local/bin/foo',
+ version: '1.0.0',
+ });
+ mgr.register(
+ {
+ detect,
+ manage: { pinnedVersion: '2.3.4', release: () => 'https://example.com/foo' },
+ name: 'foo',
+ },
+ 'browser-automation',
+ );
+
+ const status = await mgr.detect('foo');
+
+ expect(status.available).toBe(true);
+ expect(status.source).toBe('managed');
+ expect(status.path).toBe(installedPath);
+ expect(status.version).toBe('2.3.4');
+ expect(status.manageable).toBe(true);
+ // Managed cache shortcut means we never bothered the spec's detect().
+ expect(detect).not.toHaveBeenCalled();
+ });
+
+ it('marks unavailable + manageable when neither managed cache nor PATH has the binary', async () => {
+ const mgr = new BinaryManager(stubApp);
+ mgr.register(
+ {
+ detect: async () => ({ available: false }),
+ manage: { pinnedVersion: '1.0.0', release: () => 'https://example.com/foo' },
+ name: 'foo',
+ },
+ 'browser-automation',
+ );
+
+ const status = await mgr.detect('foo');
+
+ expect(status.available).toBe(false);
+ expect(status.manageable).toBe(true);
+ expect(status.source).toBeUndefined();
+ });
+ });
+
+ describe('findManagedPath / readInstalledVersion', () => {
+ it('reads back the latest installed marker', async () => {
+ const expected = await writeInstalledMarker(cacheRoot, 'foo', '9.9.9');
+ const mgr = new BinaryManager(stubApp);
+ mgr.register({ detect: async () => ({ available: false }), name: 'foo' });
+
+ await expect(mgr.findManagedPath('foo')).resolves.toBe(expected);
+ await expect(mgr.readInstalledVersion('foo')).resolves.toBe('9.9.9');
+ });
+
+ it('returns null when the marker points at a missing file', async () => {
+ const dir = path.join(cacheRoot, 'foo', '1.0.0');
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(cacheRoot, 'foo', '.installed'), '1.0.0', 'utf8');
+ // intentionally do NOT create the executable file
+
+ const mgr = new BinaryManager(stubApp);
+ mgr.register({ detect: async () => ({ available: false }), name: 'foo' });
+
+ await expect(mgr.findManagedPath('foo')).resolves.toBeNull();
+ });
+
+ it('returns null when no install marker exists', async () => {
+ const mgr = new BinaryManager(stubApp);
+ mgr.register({ detect: async () => ({ available: false }), name: 'foo' });
+
+ await expect(mgr.findManagedPath('foo')).resolves.toBeNull();
+ await expect(mgr.readInstalledVersion('foo')).resolves.toBeNull();
+ });
+ });
+
+ describe('augmentPath', () => {
+ it('appends each installed managed dir to PATH, idempotent across runs', async () => {
+ const installed = await writeInstalledMarker(cacheRoot, 'foo', '1.2.3');
+ const mgr = new BinaryManager(stubApp);
+ mgr.register({ detect: async () => ({ available: false }), name: 'foo' });
+ mgr.register({ detect: async () => ({ available: false }), name: 'bar' }); // no install
+
+ const before = process.env.PATH ?? '';
+ await mgr.augmentPath();
+
+ const sep = process.platform === 'win32' ? ';' : ':';
+ const installDir = path.dirname(installed);
+ expect((process.env.PATH ?? '').split(sep)).toContain(installDir);
+
+ // Second call must not duplicate the entry.
+ await mgr.augmentPath();
+ const segments = (process.env.PATH ?? '').split(sep);
+ expect(segments.filter((s) => s === installDir)).toHaveLength(1);
+ expect(process.env.PATH).toContain(before);
+ });
+ });
+
+ describe('ensure', () => {
+ it('returns the managed path when one is already installed', async () => {
+ const installed = await writeInstalledMarker(cacheRoot, 'foo', '0.1.0');
+ const mgr = new BinaryManager(stubApp);
+ mgr.register(
+ {
+ detect: async () => ({ available: false }),
+ manage: { pinnedVersion: '0.1.0', release: () => 'https://example.com/foo' },
+ name: 'foo',
+ },
+ 'browser-automation',
+ );
+
+ await expect(mgr.ensure('foo')).resolves.toBe(installed);
+ });
+
+ it('returns the system PATH path when no managed copy exists', async () => {
+ const mgr = new BinaryManager(stubApp);
+ mgr.register(
+ {
+ detect: async () => ({ available: true, path: '/usr/bin/foo', version: '1.0' }),
+ manage: { pinnedVersion: '2.0.0', release: () => 'https://example.com/foo' },
+ name: 'foo',
+ },
+ 'browser-automation',
+ );
+
+ await expect(mgr.ensure('foo')).resolves.toBe('/usr/bin/foo');
+ });
+
+ it('throws when the binary is unavailable AND has no manage spec', async () => {
+ const mgr = new BinaryManager(stubApp);
+ mgr.register(
+ {
+ detect: async () => ({ available: false }),
+ name: 'foo',
+ },
+ 'content-search',
+ );
+
+ await expect(mgr.ensure('foo')).rejects.toThrow(
+ /not available on the system PATH and does not opt into management/i,
+ );
+ });
+
+ it('de-dupes concurrent ensure() calls into a single install', async () => {
+ const mgr = new BinaryManager(stubApp);
+ const install = vi
+ .spyOn(mgr, 'install')
+ .mockImplementation(async (name: string) => `/managed/${name}`);
+
+ mgr.register(
+ {
+ detect: async () => ({ available: false }),
+ manage: { pinnedVersion: '1.0.0', release: () => 'https://example.com/foo' },
+ name: 'foo',
+ },
+ 'browser-automation',
+ );
+
+ const [a, b, c] = await Promise.all([
+ mgr.ensure('foo'),
+ mgr.ensure('foo'),
+ mgr.ensure('foo'),
+ ]);
+
+ expect(a).toBe('/managed/foo');
+ expect(b).toBe(a);
+ expect(c).toBe(a);
+ expect(install).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('install', () => {
+ it('throws for unmanageable binaries', async () => {
+ const mgr = new BinaryManager(stubApp);
+ mgr.register({ detect: async () => ({ available: false }), name: 'foo' });
+ await expect(mgr.install('foo')).rejects.toThrow(/not manageable/i);
+ });
+ });
+
+ describe('upgrade', () => {
+ it('no-ops when the requested version matches the installed marker', async () => {
+ const installed = await writeInstalledMarker(cacheRoot, 'foo', '5.5.5');
+ const mgr = new BinaryManager(stubApp);
+ const installSpy = vi.spyOn(mgr, 'install');
+ mgr.register(
+ {
+ detect: async () => ({ available: false }),
+ manage: { pinnedVersion: '5.5.5', release: () => 'https://example.com/foo' },
+ name: 'foo',
+ },
+ 'browser-automation',
+ );
+
+ await expect(mgr.upgrade('foo', '5.5.5')).resolves.toBe(installed);
+ expect(installSpy).not.toHaveBeenCalled();
+ });
+ });
+});
+
+describe('defineCommandBinary', () => {
+ it('passes manage spec through unchanged', () => {
+ const manage = {
+ pinnedVersion: '1.0.0',
+ release: () => 'https://example.com',
+ };
+ const spec = defineCommandBinary('demo', { description: 'demo', manage, priority: 7 });
+ expect(spec.name).toBe('demo');
+ expect(spec.description).toBe('demo');
+ expect(spec.priority).toBe(7);
+ expect(spec.manage).toBe(manage);
+ });
+});
diff --git a/apps/desktop/src/main/modules/toolDetectors/__tests__/cliAgentDetectors.test.ts b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts
similarity index 88%
rename from apps/desktop/src/main/modules/toolDetectors/__tests__/cliAgentDetectors.test.ts
rename to apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts
index 343fd5670b2..b4b99863f75 100644
--- a/apps/desktop/src/main/modules/toolDetectors/__tests__/cliAgentDetectors.test.ts
+++ b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts
@@ -44,7 +44,7 @@ const callExec = (stdout: string, stderr = '') => {
}) as any);
};
-describe('cliAgentDetectors', () => {
+describe('cliAgentBinaries', () => {
beforeEach(() => {
execFileMock.mockReset();
execMock.mockReset();
@@ -65,8 +65,8 @@ describe('cliAgentDetectors', () => {
// 2) `cmd /c "...\\claude.cmd" --version` β†’ keyword match
callExec('1.2.3 (Claude Code)');
- const { claudeCodeDetector } = await import('../cliAgentDetectors');
- const status = await claudeCodeDetector.detect();
+ const { claudeCodeBinary } = await import('../cliAgentBinaries');
+ const status = await claudeCodeBinary.detect();
expect(status.available).toBe(true);
expect(status.path).toBe('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd');
@@ -82,8 +82,8 @@ describe('cliAgentDetectors', () => {
it('returns unavailable when `where` finds nothing', async () => {
callExecFileError(new Error('not found'));
- const { claudeCodeDetector } = await import('../cliAgentDetectors');
- const status = await claudeCodeDetector.detect();
+ const { claudeCodeBinary } = await import('../cliAgentBinaries');
+ const status = await claudeCodeBinary.detect();
expect(status.available).toBe(false);
// We should NOT proceed to invoke anything after a failed resolve.
@@ -91,7 +91,7 @@ describe('cliAgentDetectors', () => {
});
it('rejects custom commands containing shell metacharacters', async () => {
- const { detectHeterogeneousCliCommand } = await import('../cliAgentDetectors');
+ const { detectHeterogeneousCliCommand } = await import('../cliAgentBinaries');
const status = await detectHeterogeneousCliCommand('claude-code', 'claude & calc.exe');
expect(status.available).toBe(false);
@@ -103,8 +103,8 @@ describe('cliAgentDetectors', () => {
callExecFile('C:\\some\\other\\claude.cmd\r\n');
callExec('this is some other binary v1.0');
- const { claudeCodeDetector } = await import('../cliAgentDetectors');
- const status = await claudeCodeDetector.detect();
+ const { claudeCodeBinary } = await import('../cliAgentBinaries');
+ const status = await claudeCodeBinary.detect();
expect(status.available).toBe(false);
});
@@ -122,8 +122,8 @@ describe('cliAgentDetectors', () => {
);
callExec('codex 0.130.0');
- const { codexDetector } = await import('../cliAgentDetectors');
- const status = await codexDetector.detect();
+ const { codexBinary } = await import('../cliAgentBinaries');
+ const status = await codexBinary.detect();
expect(status.available).toBe(true);
expect(status.path).toBe('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd');
@@ -136,8 +136,8 @@ describe('cliAgentDetectors', () => {
callExecFile(['C:\\tools\\foo.exe', 'C:\\tools\\foo.cmd'].join('\r\n'));
callExecFile('claude code 1.0.0');
- const { claudeCodeDetector } = await import('../cliAgentDetectors');
- const status = await claudeCodeDetector.detect();
+ const { claudeCodeBinary } = await import('../cliAgentBinaries');
+ const status = await claudeCodeBinary.detect();
expect(status.available).toBe(true);
expect(status.path).toBe('C:\\tools\\foo.exe');
@@ -155,8 +155,8 @@ describe('cliAgentDetectors', () => {
].join('\r\n'),
);
- const { claudeCodeDetector } = await import('../cliAgentDetectors');
- const status = await claudeCodeDetector.detect();
+ const { claudeCodeBinary } = await import('../cliAgentBinaries');
+ const status = await claudeCodeBinary.detect();
expect(status.available).toBe(false);
// Must not attempt to invoke the unrunnable matches.
@@ -174,8 +174,8 @@ describe('cliAgentDetectors', () => {
callExecFile('/usr/local/bin/claude\n');
callExecFile('1.2.3 (Claude Code)');
- const { claudeCodeDetector } = await import('../cliAgentDetectors');
- const status = await claudeCodeDetector.detect();
+ const { claudeCodeBinary } = await import('../cliAgentBinaries');
+ const status = await claudeCodeBinary.detect();
expect(status.available).toBe(true);
expect(status.path).toBe('/usr/local/bin/claude');
@@ -197,8 +197,8 @@ describe('cliAgentDetectors', () => {
callExecFileError(new Error('not found')); // which codex
callExecFile('codex-cli 0.138.0'); // bundled CLI --version
- const { codexDetector } = await import('../cliAgentDetectors');
- const status = await codexDetector.detect();
+ const { codexBinary } = await import('../cliAgentBinaries');
+ const status = await codexBinary.detect();
expect(status.available).toBe(true);
expect(status.path).toBe('/Applications/Codex.app/Contents/Resources/codex');
@@ -227,8 +227,8 @@ describe('cliAgentDetectors', () => {
callExecFileError(new Error('ENOENT')); // /Applications candidate
callExecFileError(new Error('ENOENT')); // ~/Applications candidate
- const { codexDetector } = await import('../cliAgentDetectors');
- const status = await codexDetector.detect();
+ const { codexBinary } = await import('../cliAgentBinaries');
+ const status = await codexBinary.detect();
expect(status.available).toBe(false);
expect(execFileMock).toHaveBeenCalledTimes(3);
@@ -245,7 +245,7 @@ describe('cliAgentDetectors', () => {
it('does not probe well-known locations for an explicit path-like command', async () => {
callExecFileError(new Error('ENOENT')); // /custom/bin/codex --version
- const { detectHeterogeneousCliCommand } = await import('../cliAgentDetectors');
+ const { detectHeterogeneousCliCommand } = await import('../cliAgentBinaries');
const status = await detectHeterogeneousCliCommand('codex', '/custom/bin/codex');
expect(status.available).toBe(false);
@@ -265,8 +265,8 @@ describe('cliAgentDetectors', () => {
callExecFile('/Users/Hanam/.local/share/mise/shims/gemini\n');
callExecFile('gemini 0.2.0');
- const { geminiCliDetector } = await import('../cliAgentDetectors');
- const status = await geminiCliDetector.detect();
+ const { geminiCliBinary } = await import('../cliAgentBinaries');
+ const status = await geminiCliBinary.detect();
expect(status.available).toBe(true);
expect(status.path).toBe('/Users/Hanam/.local/share/mise/shims/gemini');
diff --git a/apps/desktop/src/main/modules/binaries/agentBrowserBinaries.ts b/apps/desktop/src/main/modules/binaries/agentBrowserBinaries.ts
new file mode 100644
index 00000000000..dd7c32c2fd8
--- /dev/null
+++ b/apps/desktop/src/main/modules/binaries/agentBrowserBinaries.ts
@@ -0,0 +1,36 @@
+import type { BinarySpec } from '@/core/infrastructure/BinaryManager';
+import { defineCommandBinary } from '@/core/infrastructure/BinaryManager';
+
+/**
+ * agent-browser β€” headless browser automation CLI for AI agents.
+ *
+ * Self-hosting: the desktop app downloads the GitHub release on first use
+ * (lazy install). Users who installed via `npm i -g agent-browser`,
+ * `brew install agent-browser`, or `cargo install agent-browser` keep using
+ * their system copy β€” detect() reports those before the manager considers
+ * downloading anything.
+ *
+ * https://github.com/vercel-labs/agent-browser
+ */
+export const agentBrowserBinary: BinarySpec = defineCommandBinary('agent-browser', {
+ description: 'Vercel agent-browser - headless browser automation for AI agents',
+ manage: {
+ githubRepo: 'vercel-labs/agent-browser',
+ pinnedVersion: '0.31.1',
+ postInstall: [['install']],
+ release: ({ arch, platform, version }) => {
+ const platformSlug = ({ darwin: 'darwin', linux: 'linux', win32: 'win32' } as const)[
+ platform as 'darwin' | 'linux' | 'win32'
+ ];
+ const archSlug = ({ arm64: 'arm64', x64: 'x64' } as const)[arch as 'arm64' | 'x64'];
+ if (!platformSlug || !archSlug) {
+ throw new Error(`agent-browser: unsupported platform '${platform}-${arch}'`);
+ }
+ const exe = platform === 'win32' ? '.exe' : '';
+ return `https://github.com/vercel-labs/agent-browser/releases/download/v${version}/agent-browser-${platformSlug}-${archSlug}${exe}`;
+ },
+ },
+ priority: 1,
+});
+
+export const browserAutomationBinaries: BinarySpec[] = [agentBrowserBinary];
diff --git a/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
similarity index 90%
rename from apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts
rename to apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
index 712eee9e292..2770af1f38a 100644
--- a/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts
+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
@@ -3,8 +3,8 @@ import { homedir, platform } from 'node:os';
import path from 'node:path';
import { promisify } from 'node:util';
-import type { IToolDetector, ToolStatus } from '@/core/infrastructure/ToolDetectorManager';
-import { createCommandDetector } from '@/core/infrastructure/ToolDetectorManager';
+import type { BinarySpec, BinaryStatus } from '@/core/infrastructure/BinaryManager';
+import { defineCommandBinary } from '@/core/infrastructure/BinaryManager';
const execFilePromise = promisify(execFile);
const execPromise = promisify(exec);
@@ -152,7 +152,7 @@ const resolveCommandPath = async (command: string): Promise<ResolvedCommand | un
const detectValidatedCommand = async (
command: string,
options: Pick<ValidatedDetectorOptions, 'validateFlag' | 'validateKeywords'>,
-): Promise<ToolStatus> => {
+): Promise<BinaryStatus> => {
const trimmedCommand = command.trim();
if (!trimmedCommand) return { available: false };
if (isWindows() && WINDOWS_SHELL_METAS.test(trimmedCommand)) return { available: false };
@@ -238,7 +238,7 @@ const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[
export const detectHeterogeneousCliCommand = async (
agentType: HeterogeneousCliAgentType,
command: string,
-): Promise<ToolStatus> => {
+): Promise<BinaryStatus> => {
const validator = HETEROGENEOUS_CLI_AGENT_OPTIONS[agentType];
if (!validator) return { available: false };
@@ -259,20 +259,20 @@ export const detectHeterogeneousCliCommand = async (
};
/**
- * Detector that resolves a command path via which/where, then validates
+ * Binary spec that resolves a command path via which/where, then validates
* the binary by matching `--version` (or `--help`) output against a keyword
* to avoid collisions with unrelated executables of the same name.
*/
-const createValidatedDetector = (
+const defineValidatedBinary = (
options: ValidatedDetectorOptions & {
candidates: string[];
},
-): IToolDetector => {
+): BinarySpec => {
const { candidates, description, name, priority, ...validation } = options;
return {
description,
- async detect(): Promise<ToolStatus> {
+ async detect(): Promise<BinaryStatus> {
for (const cmd of candidates) {
const status = await detectValidatedCommand(cmd, validation);
if (status.available) return status;
@@ -289,7 +289,7 @@ const createValidatedDetector = (
* Claude Code CLI
* @see https://docs.claude.com/en/docs/claude-code
*/
-export const claudeCodeDetector: IToolDetector = createValidatedDetector({
+export const claudeCodeBinary: BinarySpec = defineValidatedBinary({
candidates: ['claude'],
description: 'Claude Code - Anthropic official agentic coding CLI',
name: 'claude',
@@ -305,7 +305,7 @@ export const claudeCodeDetector: IToolDetector = createValidatedDetector({
* fallback applies here too, keeping the manager path and the custom-command
* path in sync.
*/
-export const codexDetector: IToolDetector = {
+export const codexBinary: BinarySpec = {
description: 'Codex - OpenAI agentic coding CLI',
detect: () => detectHeterogeneousCliCommand('codex', 'codex'),
name: 'codex',
@@ -316,7 +316,7 @@ export const codexDetector: IToolDetector = {
* Google Gemini CLI
* @see https://github.com/google-gemini/gemini-cli
*/
-export const geminiCliDetector: IToolDetector = createValidatedDetector({
+export const geminiCliBinary: BinarySpec = defineValidatedBinary({
candidates: ['gemini'],
description: 'Gemini CLI - Google agentic coding CLI',
name: 'gemini',
@@ -328,7 +328,7 @@ export const geminiCliDetector: IToolDetector = createValidatedDetector({
* Qwen Code CLI
* @see https://github.com/QwenLM/qwen-code
*/
-export const qwenCodeDetector: IToolDetector = createValidatedDetector({
+export const qwenCodeBinary: BinarySpec = defineValidatedBinary({
candidates: ['qwen'],
description: 'Qwen Code - Alibaba Qwen agentic coding CLI',
name: 'qwen',
@@ -340,7 +340,7 @@ export const qwenCodeDetector: IToolDetector = createValidatedDetector({
* Kimi CLI (Moonshot)
* @see https://github.com/MoonshotAI/kimi-cli
*/
-export const kimiCliDetector: IToolDetector = createValidatedDetector({
+export const kimiCliBinary: BinarySpec = defineValidatedBinary({
candidates: ['kimi'],
description: 'Kimi CLI - Moonshot AI agentic coding CLI',
name: 'kimi',
@@ -350,22 +350,22 @@ export const kimiCliDetector: IToolDetector = createValidatedDetector({
/**
* Aider - AI pair programming CLI
- * Generic command detector; name collision is unlikely.
+ * Generic command spec; name collision is unlikely.
* @see https://github.com/Aider-AI/aider
*/
-export const aiderDetector: IToolDetector = createCommandDetector('aider', {
+export const aiderBinary: BinarySpec = defineCommandBinary('aider', {
description: 'Aider - AI pair programming in your terminal',
priority: 6,
});
/**
- * All CLI agent detectors
+ * All CLI agent binaries
*/
-export const cliAgentDetectors: IToolDetector[] = [
- claudeCodeDetector,
- codexDetector,
- geminiCliDetector,
- qwenCodeDetector,
- kimiCliDetector,
- aiderDetector,
+export const cliAgentBinaries: BinarySpec[] = [
+ claudeCodeBinary,
+ codexBinary,
+ geminiCliBinary,
+ qwenCodeBinary,
+ kimiCliBinary,
+ aiderBinary,
];
diff --git a/apps/desktop/src/main/modules/binaries/contentSearchBinaries.ts b/apps/desktop/src/main/modules/binaries/contentSearchBinaries.ts
new file mode 100644
index 00000000000..5987c24dfbf
--- /dev/null
+++ b/apps/desktop/src/main/modules/binaries/contentSearchBinaries.ts
@@ -0,0 +1,54 @@
+import type { BinarySpec } from '@/core/infrastructure/BinaryManager';
+import { defineCommandBinary } from '@/core/infrastructure/BinaryManager';
+
+/**
+ * Content search binaries
+ *
+ * Priority order: rg (1) > ag (2) > grep (3)
+ * AST search: sg (ast-grep) - separate category for AST-based code search
+ */
+
+/**
+ * ripgrep (rg) - Fastest grep alternative
+ * https://github.com/BurntSushi/ripgrep
+ */
+export const ripgrepBinary: BinarySpec = defineCommandBinary('rg', {
+ description: 'ripgrep - fast grep alternative',
+ priority: 1,
+});
+
+/**
+ * ast-grep (sg) - AST-based code search tool
+ * https://ast-grep.github.io/
+ */
+export const astGrepBinary: BinarySpec = defineCommandBinary('sg', {
+ description: 'ast-grep - AST-based code search',
+ priority: 1,
+});
+
+/**
+ * The Silver Searcher (ag) - Fast code searching tool
+ * https://github.com/ggreer/the_silver_searcher
+ */
+export const agBinary: BinarySpec = defineCommandBinary('ag', {
+ description: 'The Silver Searcher',
+ priority: 2,
+});
+
+/**
+ * GNU grep - Standard text search tool
+ */
+export const grepBinary: BinarySpec = defineCommandBinary('grep', {
+ description: 'GNU grep',
+ priority: 3,
+});
+
+/**
+ * All content search binaries (text-based grep tools)
+ */
+export const contentSearchBinaries: BinarySpec[] = [ripgrepBinary, agBinary, grepBinary];
+
+/**
+ * AST-based code search binaries
+ */
+export const astSearchBinaries: BinarySpec[] = [astGrepBinary];
diff --git a/apps/desktop/src/main/modules/toolDetectors/fileSearchDetectors.ts b/apps/desktop/src/main/modules/binaries/fileSearchBinaries.ts
similarity index 62%
rename from apps/desktop/src/main/modules/toolDetectors/fileSearchDetectors.ts
rename to apps/desktop/src/main/modules/binaries/fileSearchBinaries.ts
index 162a8a0a367..fb639b5b3df 100644
--- a/apps/desktop/src/main/modules/toolDetectors/fileSearchDetectors.ts
+++ b/apps/desktop/src/main/modules/binaries/fileSearchBinaries.ts
@@ -1,17 +1,13 @@
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
-import type {
- IToolDetector,
- ToolStatus} from '@/core/infrastructure/ToolDetectorManager';
-import {
- createCommandDetector
-} from '@/core/infrastructure/ToolDetectorManager';
+import type { BinarySpec, BinaryStatus } from '@/core/infrastructure/BinaryManager';
+import { defineCommandBinary } from '@/core/infrastructure/BinaryManager';
const execPromise = promisify(exec);
/**
- * File search tool detectors
+ * File search binaries
*
* Priority order: mdfind (1, macOS) > fd (2) > find (3)
*/
@@ -20,10 +16,9 @@ const execPromise = promisify(exec);
* mdfind - macOS Spotlight search
* Only available on macOS, uses Spotlight index for fast searching
*/
-export const mdfindDetector: IToolDetector = {
+export const mdfindBinary: BinarySpec = {
description: 'macOS Spotlight search',
- async detect(): Promise<ToolStatus> {
- // Only available on macOS
+ async detect(): Promise<BinaryStatus> {
if (process.platform !== 'darwin') {
return {
available: false,
@@ -32,12 +27,10 @@ export const mdfindDetector: IToolDetector = {
}
try {
- // Check if mdfind command exists and Spotlight is working
const { stdout } = await execPromise('mdfind -name test -onlyin ~ -count', {
timeout: 5000,
});
- // If mdfind returns a number (even 0), Spotlight is available
const count = parseInt(stdout.trim(), 10);
if (Number.isNaN(count)) {
return {
@@ -65,7 +58,7 @@ export const mdfindDetector: IToolDetector = {
* fd - Fast alternative to find
* https://github.com/sharkdp/fd
*/
-export const fdDetector: IToolDetector = createCommandDetector('fd', {
+export const fdBinary: BinarySpec = defineCommandBinary('fd', {
description: 'fd - fast find alternative',
priority: 2,
});
@@ -73,13 +66,13 @@ export const fdDetector: IToolDetector = createCommandDetector('fd', {
/**
* find - Standard Unix file search
*/
-export const findDetector: IToolDetector = createCommandDetector('find', {
+export const findBinary: BinarySpec = defineCommandBinary('find', {
description: 'Unix find command',
priority: 3,
- versionFlag: '--version', // GNU find supports this
+ versionFlag: '--version',
});
/**
- * All file search detectors
+ * All file search binaries
*/
-export const fileSearchDetectors: IToolDetector[] = [mdfindDetector, fdDetector, findDetector];
+export const fileSearchBinaries: BinarySpec[] = [mdfindBinary, fdBinary, findBinary];
diff --git a/apps/desktop/src/main/modules/binaries/index.ts b/apps/desktop/src/main/modules/binaries/index.ts
new file mode 100644
index 00000000000..5b5e20e352f
--- /dev/null
+++ b/apps/desktop/src/main/modules/binaries/index.ts
@@ -0,0 +1,14 @@
+/**
+ * Binaries module
+ *
+ * Built-in binary specs for the desktop's BinaryManager. Other modules can
+ * register additional custom specs via the manager directly.
+ */
+
+export { browserAutomationBinaries } from './agentBrowserBinaries';
+export { cliAgentBinaries, detectHeterogeneousCliCommand } from './cliAgentBinaries';
+export { astSearchBinaries, contentSearchBinaries } from './contentSearchBinaries';
+export { fileSearchBinaries } from './fileSearchBinaries';
+export { runtimeEnvironmentBinaries } from './runtimeEnvironmentBinaries';
+export type { BinaryCategory, BinarySpec, BinaryStatus } from '@/core/infrastructure/BinaryManager';
+export { defineCommandBinary } from '@/core/infrastructure/BinaryManager';
diff --git a/apps/desktop/src/main/modules/toolDetectors/runtimeEnvironmentDetectors.ts b/apps/desktop/src/main/modules/binaries/runtimeEnvironmentBinaries.ts
similarity index 68%
rename from apps/desktop/src/main/modules/toolDetectors/runtimeEnvironmentDetectors.ts
rename to apps/desktop/src/main/modules/binaries/runtimeEnvironmentBinaries.ts
index e0fce4be79c..58c2ba0ea58 100644
--- a/apps/desktop/src/main/modules/toolDetectors/runtimeEnvironmentDetectors.ts
+++ b/apps/desktop/src/main/modules/binaries/runtimeEnvironmentBinaries.ts
@@ -2,34 +2,34 @@ import { exec } from 'node:child_process';
import { platform } from 'node:os';
import { promisify } from 'node:util';
-import type { IToolDetector, ToolStatus } from '@/core/infrastructure/ToolDetectorManager';
-import { createCommandDetector } from '@/core/infrastructure/ToolDetectorManager';
+import type { BinarySpec, BinaryStatus } from '@/core/infrastructure/BinaryManager';
+import { defineCommandBinary } from '@/core/infrastructure/BinaryManager';
const execPromise = promisify(exec);
/**
- * Node.js runtime detector
+ * Node.js runtime
*/
-export const nodeDetector: IToolDetector = createCommandDetector('node', {
+export const nodeBinary: BinarySpec = defineCommandBinary('node', {
description: 'Node.js - JavaScript runtime',
priority: 1,
});
/**
- * NPM package manager detector
+ * NPM package manager
*/
-export const npmDetector: IToolDetector = createCommandDetector('npm', {
+export const npmBinary: BinarySpec = defineCommandBinary('npm', {
description: 'npm - Node.js package manager',
priority: 2,
});
/**
- * Python runtime detector
+ * Python runtime
* Tries python3 (Unix) first, then python (cross-platform)
*/
-export const pythonDetector: IToolDetector = {
+export const pythonBinary: BinarySpec = {
description: 'Python - programming language runtime',
- async detect(): Promise<ToolStatus> {
+ async detect(): Promise<BinaryStatus> {
const commands = platform() === 'win32' ? ['python', 'py'] : ['python3', 'python'];
for (const cmd of commands) {
@@ -64,44 +64,44 @@ export const pythonDetector: IToolDetector = {
};
/**
- * Bun runtime detector
+ * Bun runtime
*/
-export const bunDetector: IToolDetector = createCommandDetector('bun', {
+export const bunBinary: BinarySpec = defineCommandBinary('bun', {
description: 'Bun - fast JavaScript runtime and package manager',
priority: 4,
});
/**
- * Bunx package runner detector
+ * Bunx package runner
*/
-export const bunxDetector: IToolDetector = createCommandDetector('bunx', {
+export const bunxBinary: BinarySpec = defineCommandBinary('bunx', {
description: 'bunx - Bun package runner for executing npm packages',
priority: 5,
});
/**
- * pnpm package manager detector
+ * pnpm package manager
*/
-export const pnpmDetector: IToolDetector = createCommandDetector('pnpm', {
+export const pnpmBinary: BinarySpec = defineCommandBinary('pnpm', {
description: 'pnpm - fast, disk space efficient package manager',
priority: 6,
});
/**
- * uv Python package manager detector
+ * uv Python package manager
*/
-export const uvDetector: IToolDetector = createCommandDetector('uv', {
+export const uvBinary: BinarySpec = defineCommandBinary('uv', {
description: 'uv - extremely fast Python package manager',
priority: 7,
});
/**
- * LobeHub CLI detector
+ * LobeHub CLI
* Tries lobehub, lobe, lh in order; validates via --help output containing "LobeHub"
*/
-export const lobehubDetector: IToolDetector = {
+export const lobehubBinary: BinarySpec = {
description: 'LobeHub CLI - manage and connect to LobeHub services',
- async detect(): Promise<ToolStatus> {
+ async detect(): Promise<BinaryStatus> {
const commands = ['lobehub', 'lobe', 'lh'];
const whichCmd = platform() === 'win32' ? 'where' : 'which';
@@ -130,15 +130,15 @@ export const lobehubDetector: IToolDetector = {
};
/**
- * All runtime environment detectors
+ * All runtime environment binaries
*/
-export const runtimeEnvironmentDetectors: IToolDetector[] = [
- lobehubDetector,
- nodeDetector,
- npmDetector,
- pythonDetector,
- bunDetector,
- bunxDetector,
- pnpmDetector,
- uvDetector,
+export const runtimeEnvironmentBinaries: BinarySpec[] = [
+ lobehubBinary,
+ nodeBinary,
+ npmBinary,
+ pythonBinary,
+ bunBinary,
+ bunxBinary,
+ pnpmBinary,
+ uvBinary,
];
diff --git a/apps/desktop/src/main/modules/toolDetectors/agentBrowserDetectors.ts b/apps/desktop/src/main/modules/toolDetectors/agentBrowserDetectors.ts
deleted file mode 100644
index 6e78927436e..00000000000
--- a/apps/desktop/src/main/modules/toolDetectors/agentBrowserDetectors.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { IToolDetector } from '@/core/infrastructure/ToolDetectorManager';
-import { createCommandDetector } from '@/core/infrastructure/ToolDetectorManager';
-
-/**
- * agent-browser - Headless browser automation CLI for AI agents
- * https://github.com/vercel-labs/agent-browser
- */
-export const agentBrowserDetector: IToolDetector = createCommandDetector('agent-browser', {
- description: 'Vercel agent-browser - headless browser automation for AI agents',
- priority: 1,
-});
-
-export const browserAutomationDetectors: IToolDetector[] = [agentBrowserDetector];
diff --git a/apps/desktop/src/main/modules/toolDetectors/contentSearchDetectors.ts b/apps/desktop/src/main/modules/toolDetectors/contentSearchDetectors.ts
deleted file mode 100644
index d3b3f69becf..00000000000
--- a/apps/desktop/src/main/modules/toolDetectors/contentSearchDetectors.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import type { IToolDetector } from '@/core/infrastructure/ToolDetectorManager';
-import { createCommandDetector } from '@/core/infrastructure/ToolDetectorManager';
-
-/**
- * Content search tool detectors
- *
- * Priority order: rg (1) > ag (2) > grep (3)
- * AST search: sg (ast-grep) - separate category for AST-based code search
- */
-
-/**
- * ripgrep (rg) - Fastest grep alternative
- * https://github.com/BurntSushi/ripgrep
- */
-export const ripgrepDetector: IToolDetector = createCommandDetector('rg', {
- description: 'ripgrep - fast grep alternative',
- priority: 1,
-});
-
-/**
- * ast-grep (sg) - AST-based code search tool
- * https://ast-grep.github.io/
- */
-export const astGrepDetector: IToolDetector = createCommandDetector('sg', {
- description: 'ast-grep - AST-based code search',
- priority: 1,
-});
-
-/**
- * The Silver Searcher (ag) - Fast code searching tool
- * https://github.com/ggreer/the_silver_searcher
- */
-export const agDetector: IToolDetector = createCommandDetector('ag', {
- description: 'The Silver Searcher',
- priority: 2,
-});
-
-/**
- * GNU grep - Standard text search tool
- */
-export const grepDetector: IToolDetector = createCommandDetector('grep', {
- description: 'GNU grep',
- priority: 3,
-});
-
-/**
- * All content search detectors (text-based grep tools)
- */
-export const contentSearchDetectors: IToolDetector[] = [ripgrepDetector, agDetector, grepDetector];
-
-/**
- * AST-based code search detectors
- */
-export const astSearchDetectors: IToolDetector[] = [astGrepDetector];
diff --git a/apps/desktop/src/main/modules/toolDetectors/index.ts b/apps/desktop/src/main/modules/toolDetectors/index.ts
deleted file mode 100644
index 6ac7c3e357a..00000000000
--- a/apps/desktop/src/main/modules/toolDetectors/index.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * Tool Detectors Module
- *
- * This module provides built-in tool detectors for common system tools.
- * Modules can register additional custom detectors via ToolDetectorManager.
- */
-
-export { browserAutomationDetectors } from './agentBrowserDetectors';
-export { cliAgentDetectors, detectHeterogeneousCliCommand } from './cliAgentDetectors';
-export { astSearchDetectors, contentSearchDetectors } from './contentSearchDetectors';
-export { fileSearchDetectors } from './fileSearchDetectors';
-export { runtimeEnvironmentDetectors } from './runtimeEnvironmentDetectors';
-
-// Re-export types for convenience
-export type {
- IToolDetector,
- ToolCategory,
- ToolStatus,
-} from '@/core/infrastructure/ToolDetectorManager';
-export { createCommandDetector } from '@/core/infrastructure/ToolDetectorManager';
diff --git a/apps/desktop/src/main/services/contentSearchSrv.ts b/apps/desktop/src/main/services/contentSearchSrv.ts
index 8f9d5b2aa10..a558191b293 100644
--- a/apps/desktop/src/main/services/contentSearchSrv.ts
+++ b/apps/desktop/src/main/services/contentSearchSrv.ts
@@ -16,12 +16,12 @@ export default class ContentSearchService extends ServiceModule {
private impl: BaseContentSearch = createContentSearchImpl();
async grep(params: GrepContentParams): Promise<GrepContentResult> {
- // Lazily wire the desktop ToolDetectorManager so we don't hit the
+ // Lazily wire the desktop BinaryManager so we don't hit the
// class-field init-before-super-constructor gotcha. The manager already
// satisfies the minimal `ToolDetector` contract (only `getBestTool` is
// consumed by the search impls).
- if (this.app?.toolDetectorManager) {
- this.impl.setToolDetector(this.app.toolDetectorManager);
+ if (this.app?.binaryManager) {
+ this.impl.setToolDetector(this.app.binaryManager);
}
return this.impl.grep(params);
}
diff --git a/apps/desktop/src/main/services/fileSearchSrv.ts b/apps/desktop/src/main/services/fileSearchSrv.ts
index c8e84b0f7ca..253988c7dbc 100644
--- a/apps/desktop/src/main/services/fileSearchSrv.ts
+++ b/apps/desktop/src/main/services/fileSearchSrv.ts
@@ -21,8 +21,8 @@ export default class FileSearchService extends ServiceModule {
query: string,
options: Omit<SearchOptions, 'keywords'> = {},
): Promise<FileResult[]> {
- if (this.app?.toolDetectorManager) {
- this.impl.setToolDetector(this.app.toolDetectorManager);
+ if (this.app?.binaryManager) {
+ this.impl.setToolDetector(this.app.binaryManager);
}
return this.impl.search({ ...options, keywords: query });
}
@@ -36,8 +36,8 @@ export default class FileSearchService extends ServiceModule {
}
async glob(params: GlobFilesParams): Promise<GlobFilesResult> {
- if (this.app?.toolDetectorManager) {
- this.impl.setToolDetector(this.app.toolDetectorManager);
+ if (this.app?.binaryManager) {
+ this.impl.setToolDetector(this.app.binaryManager);
}
return this.impl.glob(params);
}
diff --git a/packages/builtin-skills/src/agent-browser/content.ts b/packages/builtin-skills/src/agent-browser/content.ts
index b6314f1ac7f..0948ae4decf 100644
--- a/packages/builtin-skills/src/agent-browser/content.ts
+++ b/packages/builtin-skills/src/agent-browser/content.ts
@@ -1,819 +1,22 @@
-/**
- * Synced from https://github.com/vercel-labs/agent-browser/blob/main/skills/agent-browser/SKILL.md
- */
export const systemPrompt = `<agent_browser_guides>
-# Browser Automation with agent-browser
+# agent-browser
-The CLI uses Chrome/Chromium via CDP directly. **LobeHub desktop** bundles \`agent-browser\` in native mode. Otherwise install via \`npm i -g agent-browser\`, \`brew install agent-browser\`, or \`cargo install agent-browser\`. Run \`agent-browser install\` to download Chrome. Existing Chrome, Brave, Playwright, and Puppeteer installations are detected automatically. Run \`agent-browser upgrade\` to update to the latest version.
+\`agent-browser\` is a fast browser automation CLI for AI agents β€” drives Chrome/Chromium via CDP and serves accessibility-tree snapshots with compact \`@eN\` element refs (so you act on the page in a few hundred tokens, not raw HTML).
-## Core Workflow
+LobeHub desktop bundles \`agent-browser\` natively β€” no install needed. Outside LobeHub, install with \`npm i -g agent-browser\` (or \`brew install agent-browser\` / \`cargo install agent-browser\`), then run \`agent-browser install\` once to fetch the bundled Chrome.
-Every browser automation follows this pattern:
-
-1. **Navigate**: \`agent-browser open <url>\`
-2. **Snapshot**: \`agent-browser snapshot -i\` (get element refs like \`@e1\`, \`@e2\`)
-3. **Interact**: Use refs to click, fill, select
-4. **Re-snapshot**: After navigation or DOM changes, get fresh refs
-
-\`\`\`bash
-agent-browser open https://example.com/form
-agent-browser snapshot -i
-# Output: @e1 [input type="email"], @e2 [input type="password"], @e3 [button] "Submit"
-
-agent-browser fill @e1 "[email protected]"
-agent-browser fill @e2 "your-password"
-agent-browser click @e3
-agent-browser wait 2000
-agent-browser snapshot -i # Check result
-\`\`\`
-
-## Command Chaining
-
-Commands can be chained with \`&&\` in a single shell invocation. The browser persists between commands via a background daemon, so chaining is safe and more efficient than separate calls.
-
-\`\`\`bash
-# Chain open + snapshot in one call (open already waits for page load)
-agent-browser open https://example.com && agent-browser snapshot -i
-
-# Chain multiple interactions
-agent-browser fill @e1 "[email protected]" && agent-browser fill @e2 "your-password" && agent-browser click @e3
-
-# Navigate and capture
-agent-browser open https://example.com && agent-browser screenshot
-\`\`\`
-
-**When to chain:** Use \`&&\` when you don't need to read the output of an intermediate command before proceeding (e.g., open + wait + screenshot). Run commands separately when you need to parse the output first (e.g., snapshot to discover refs, then interact using those refs).
-
-## Handling Authentication
-
-When automating a site that requires login, choose the approach that fits:
-
-**Option 1: Import auth from the user's browser (fastest for one-off tasks)**
-
-\`\`\`bash
-# Connect to the user's running Chrome (they're already logged in)
-agent-browser --auto-connect state save ./auth.json
-# Use that auth state
-agent-browser --state ./auth.json open https://example.com/dashboard
-\`\`\`
-
-State files contain session tokens in plaintext -- add to \`.gitignore\` and delete when no longer needed. Set \`AGENT_BROWSER_ENCRYPTION_KEY\` for encryption at rest.
-
-**Option 2: Chrome profile reuse (zero setup)**
-
-\`\`\`bash
-# List available Chrome profiles
-agent-browser profiles
-
-# Reuse the user's existing Chrome login state
-agent-browser --profile Default open https://gmail.com
-\`\`\`
-
-**Option 3: Persistent profile (for recurring tasks)**
-
-\`\`\`bash
-# First run: login manually or via automation
-agent-browser --profile ~/.myapp open https://example.com/login
-# ... fill credentials, submit ...
-
-# All future runs: already authenticated
-agent-browser --profile ~/.myapp open https://example.com/dashboard
-\`\`\`
-
-**Option 4: Session name (auto-save/restore cookies + localStorage)**
-
-\`\`\`bash
-agent-browser --session-name myapp open https://example.com/login
-# ... login flow ...
-agent-browser close # State auto-saved
-
-# Next time: state auto-restored
-agent-browser --session-name myapp open https://example.com/dashboard
-\`\`\`
-
-**Option 5: Auth vault (credentials stored encrypted, login by name)**
-
-\`\`\`bash
-echo "$PASSWORD" | agent-browser auth save myapp --url https://app.example.com/login --username user --password-stdin
-agent-browser auth login myapp
-\`\`\`
-
-\`auth login\` navigates with \`load\` and then waits for login form selectors to appear before filling/clicking, which is more reliable on delayed SPA login screens.
-
-**Option 6: State file (manual save/load)**
-
-\`\`\`bash
-# After logging in:
-agent-browser state save ./auth.json
-# In a future session:
-agent-browser state load ./auth.json
-agent-browser open https://example.com/dashboard
-\`\`\`
-
-For OAuth, 2FA, cookie-based auth, and token refresh patterns, see the upstream \`references/authentication.md\` at https://github.com/vercel-labs/agent-browser/tree/main/skills/agent-browser/references.
-
-## Essential Commands
-
-\`\`\`bash
-# Batch: ALWAYS use batch for 2+ sequential commands. Commands run in order.
-agent-browser batch "open https://example.com" "snapshot -i"
-agent-browser batch "open https://example.com" "screenshot"
-agent-browser batch "click @e1" "wait 1000" "screenshot"
-
-# Navigation
-agent-browser open <url> # Navigate (aliases: goto, navigate)
-agent-browser close # Close browser
-agent-browser close --all # Close all active sessions
-
-# Snapshot
-agent-browser snapshot -i # Interactive elements with refs (recommended)
-agent-browser snapshot -i --urls # Include href URLs for links
-agent-browser snapshot -s "#selector" # Scope to CSS selector
-
-# Interaction (use @refs from snapshot)
-agent-browser click @e1 # Click element
-agent-browser click @e1 --new-tab # Click and open in new tab
-agent-browser fill @e2 "text" # Clear and type text
-agent-browser type @e2 "text" # Type without clearing
-agent-browser select @e1 "option" # Select dropdown option
-agent-browser check @e1 # Check checkbox
-agent-browser press Enter # Press key
-agent-browser keyboard type "text" # Type at current focus (no selector)
-agent-browser keyboard inserttext "text" # Insert without key events
-agent-browser scroll down 500 # Scroll page
-agent-browser scroll down 500 --selector "div.content" # Scroll within a specific container
-
-# Get information
-agent-browser get text @e1 # Get element text
-agent-browser get url # Get current URL
-agent-browser get title # Get page title
-agent-browser get cdp-url # Get CDP WebSocket URL
-
-# Wait
-agent-browser wait @e1 # Wait for element
-agent-browser wait 2000 # Wait milliseconds
-agent-browser wait --url "**/page" # Wait for URL pattern
-agent-browser wait --text "Welcome" # Wait for text to appear (substring match)
-agent-browser wait --load networkidle # Wait for network idle (caution: see Pitfalls)
-agent-browser wait --fn "!document.body.innerText.includes('Loading...')" # Wait for text to disappear
-agent-browser wait "#spinner" --state hidden # Wait for element to disappear
-
-# Downloads
-agent-browser download @e1 ./file.pdf # Click element to trigger download
-agent-browser wait --download ./output.zip # Wait for any download to complete
-agent-browser --download-path ./downloads open <url> # Set default download directory
-
-# Tab management
-agent-browser tab list # List all open tabs
-agent-browser tab new # Open a blank new tab
-agent-browser tab new https://example.com # Open URL in a new tab
-agent-browser tab 2 # Switch to tab by index (0-based)
-agent-browser tab close # Close the current tab
-agent-browser tab close 2 # Close tab by index
-
-# Network
-agent-browser network requests # Inspect tracked requests
-agent-browser network requests --type xhr,fetch # Filter by resource type
-agent-browser network requests --method POST # Filter by HTTP method
-agent-browser network requests --status 2xx # Filter by status (200, 2xx, 400-499)
-agent-browser network request <requestId> # View full request/response detail
-agent-browser network route "**/api/*" --abort # Block matching requests
-agent-browser network har start # Start HAR recording
-agent-browser network har stop ./capture.har # Stop and save HAR file
-
-# Viewport & Device Emulation
-agent-browser set viewport 1920 1080 # Set viewport size (default: 1280x720)
-agent-browser set viewport 1920 1080 2 # 2x retina (same CSS size, higher res screenshots)
-agent-browser set device "iPhone 14" # Emulate device (viewport + user agent)
-
-# Capture
-agent-browser screenshot # Screenshot to temp dir
-agent-browser screenshot --full # Full page screenshot
-agent-browser screenshot --annotate # Annotated screenshot with numbered element labels
-agent-browser screenshot --screenshot-dir ./shots # Save to custom directory
-agent-browser screenshot --screenshot-format jpeg --screenshot-quality 80
-agent-browser pdf output.pdf # Save as PDF
-
-# Live preview / streaming
-agent-browser stream enable # Start runtime WebSocket streaming on an auto-selected port
-agent-browser stream enable --port 9223 # Bind a specific localhost port
-agent-browser stream status # Inspect enabled state, port, connection, and screencasting
-agent-browser stream disable # Stop runtime streaming and remove the .stream metadata file
-
-# Clipboard
-agent-browser clipboard read # Read text from clipboard
-agent-browser clipboard write "Hello, World!" # Write text to clipboard
-agent-browser clipboard copy # Copy current selection
-agent-browser clipboard paste # Paste from clipboard
-
-# Dialogs (alert, confirm, prompt, beforeunload)
-# By default, alert and beforeunload dialogs are auto-accepted so they never block the agent.
-# confirm and prompt dialogs still require explicit handling.
-# Use --no-auto-dialog (or AGENT_BROWSER_NO_AUTO_DIALOG=1) to disable automatic handling.
-agent-browser dialog accept # Accept dialog
-agent-browser dialog accept "my input" # Accept prompt dialog with text
-agent-browser dialog dismiss # Dismiss/cancel dialog
-agent-browser dialog status # Check if a dialog is currently open
-
-# Diff (compare page states)
-agent-browser diff snapshot # Compare current vs last snapshot
-agent-browser diff snapshot --baseline before.txt # Compare current vs saved file
-agent-browser diff screenshot --baseline before.png # Visual pixel diff
-agent-browser diff url <url1> <url2> # Compare two pages
-agent-browser diff url <url1> <url2> --wait-until networkidle # Custom wait strategy
-agent-browser diff url <url1> <url2> --selector "#main" # Scope to element
-
-# Chat (AI natural language control)
-agent-browser chat "open google.com and search for cats" # Single-shot instruction
-agent-browser chat # Interactive REPL mode
-agent-browser -q chat "summarize this page" # Quiet (text only, no tool calls)
-agent-browser -v chat "fill in the login form" # Verbose (show command output)
-agent-browser --model openai/gpt-4o chat "take a screenshot" # Override model
-\`\`\`
-
-## Streaming
-
-Every session automatically starts a WebSocket stream server on an OS-assigned port. Use \`agent-browser stream status\` to see the bound port and connection state. Use \`stream disable\` to tear it down, and \`stream enable --port <port>\` to re-enable on a specific port.
-
-## Batch Execution
-
-ALWAYS use \`batch\` when running 2+ commands in sequence. Batch executes commands in order, so dependent commands (like navigate then screenshot) work correctly. Each quoted argument is a separate command.
-
-\`\`\`bash
-# Navigate and take a snapshot
-agent-browser batch "open https://example.com" "snapshot -i"
-
-# Navigate, snapshot, and screenshot in one call
-agent-browser batch "open https://example.com" "snapshot -i" "screenshot"
-
-# Click, wait, then screenshot
-agent-browser batch "click @e1" "wait 1000" "screenshot"
-
-# With --bail to stop on first error
-agent-browser batch --bail "open https://example.com" "click @e1" "screenshot"
-\`\`\`
-
-Only use a single command (not batch) when you need to read the output before deciding the next command. For example, you must run \`snapshot -i\` as a single command when you need to read the refs to decide what to click. After reading the snapshot, batch the remaining steps.
-
-Stdin mode is also supported for programmatic use:
-
-\`\`\`bash
-echo '[["open","https://example.com"],["screenshot"]]' | agent-browser batch --json
-agent-browser batch --bail < commands.json
-\`\`\`
-
-## Efficiency Strategies
-
-These patterns minimize tool calls and token usage.
-
-**Use \`--urls\` to avoid re-navigation.** When you need to visit links from a page, use \`snapshot -i --urls\` to get all href URLs upfront. Then \`open\` each URL directly instead of clicking refs and navigating back.
-
-**Snapshot once, act many times.** Never re-snapshot the same page. Extract all needed info (refs, URLs, text) from a single snapshot, then batch the remaining actions.
-
-**Multi-page workflow (e.g. "visit N sites and screenshot each"):**
-
-\`\`\`bash
-# 1. Get all URLs in one call
-agent-browser batch "open https://news.ycombinator.com" "snapshot -i --urls"
-# Read output to extract URLs, then visit each directly:
-# 2. One batch per target site
-agent-browser batch "open https://github.com/example/repo" "screenshot"
-agent-browser batch "open https://example.com/article" "screenshot"
-agent-browser batch "open https://other.com/page" "screenshot"
-\`\`\`
-
-This approach uses 4 tool calls instead of 14+. Never go back to the listing page between visits.
-
-## Common Patterns
-
-### Form Submission
-
-\`\`\`bash
-# Navigate and get the form structure
-agent-browser batch "open https://example.com/signup" "snapshot -i"
-# Read the snapshot output to identify form refs, then fill and submit
-agent-browser batch "fill @e1 \\"Jane Doe\\"" "fill @e2 \\"[email protected]\\"" "select @e3 \\"California\\"" "check @e4" "click @e5" "wait 2000"
-\`\`\`
-
-### Authentication with Auth Vault (Recommended)
+## The core loop
\`\`\`bash
-# Save credentials once (encrypted with AGENT_BROWSER_ENCRYPTION_KEY)
-# Recommended: pipe password via stdin to avoid shell history exposure
-echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin
-
-# Login using saved profile (LLM never sees password)
-agent-browser auth login github
-
-# List/show/delete profiles
-agent-browser auth list
-agent-browser auth show github
-agent-browser auth delete github
-\`\`\`
-
-\`auth login\` waits for username/password/submit selectors before interacting, with a timeout tied to the default action timeout.
-
-### Authentication with State Persistence
-
-\`\`\`bash
-# Login once and save state
-agent-browser batch "open https://example.com/login" "snapshot -i"
-# Read snapshot to find form refs, then fill and submit
-agent-browser batch "fill @e1 \\"$USERNAME\\"" "fill @e2 \\"$PASSWORD\\"" "click @e3" "wait --url **/dashboard" "state save auth.json"
-
-# Reuse in future sessions
-agent-browser batch "state load auth.json" "open https://example.com/dashboard"
-\`\`\`
-
-### Session Persistence
-
-\`\`\`bash
-# Auto-save/restore cookies and localStorage across browser restarts
-agent-browser --session-name myapp open https://example.com/login
-# ... login flow ...
-agent-browser close # State auto-saved to ~/.agent-browser/sessions/
-
-# Next time, state is auto-loaded
-agent-browser --session-name myapp open https://example.com/dashboard
-
-# Encrypt state at rest
-export AGENT_BROWSER_ENCRYPTION_KEY=$(openssl rand -hex 32)
-agent-browser --session-name secure open https://example.com
-
-# Manage saved states
-agent-browser state list
-agent-browser state show myapp-default.json
-agent-browser state clear myapp
-agent-browser state clean --older-than 7
-\`\`\`
-
-### Working with Iframes
-
-Iframe content is automatically inlined in snapshots. Refs inside iframes carry frame context, so you can interact with them directly.
-
-\`\`\`bash
-agent-browser batch "open https://example.com/checkout" "snapshot -i"
-# @e1 [heading] "Checkout"
-# @e2 [Iframe] "payment-frame"
-# @e3 [input] "Card number"
-# @e4 [input] "Expiry"
-# @e5 [button] "Pay"
-
-# Interact directly β€” no frame switch needed
-agent-browser batch "fill @e3 \\"4111111111111111\\"" "fill @e4 \\"12/28\\"" "click @e5"
-
-# To scope a snapshot to one iframe:
-agent-browser batch "frame @e2" "snapshot -i"
-agent-browser frame main # Return to main frame
+agent-browser open <url> # 1. navigate
+agent-browser snapshot -i # 2. see interactive elements (@e1, @e2, …)
+agent-browser click @e3 # 3. act on a ref
+agent-browser snapshot -i # 4. re-snapshot after any page change
\`\`\`
-### Data Extraction
-
-\`\`\`bash
-agent-browser batch "open https://example.com/products" "snapshot -i"
-# Read snapshot to find element refs, then extract
-agent-browser get text @e5 # Get specific element text
-
-# JSON output for parsing
-agent-browser snapshot -i --json
-agent-browser get text @e1 --json
-\`\`\`
-
-### Parallel Sessions
-
-\`\`\`bash
-agent-browser --session site1 open https://site-a.com
-agent-browser --session site2 open https://site-b.com
-
-agent-browser --session site1 snapshot -i
-agent-browser --session site2 snapshot -i
-
-agent-browser session list
-\`\`\`
-
-### Connect to Existing Chrome
-
-\`\`\`bash
-# Auto-discover running Chrome with remote debugging enabled
-agent-browser --auto-connect open https://example.com
-agent-browser --auto-connect snapshot
-
-# Or with explicit CDP port
-agent-browser --cdp 9222 snapshot
-\`\`\`
-
-Auto-connect discovers Chrome via \`DevToolsActivePort\`, common debugging ports (9222, 9229), and falls back to a direct WebSocket connection if HTTP-based CDP discovery fails.
-
-### Color Scheme (Dark Mode)
-
-\`\`\`bash
-# Persistent dark mode via flag (applies to all pages and new tabs)
-agent-browser --color-scheme dark open https://example.com
-
-# Or via environment variable
-AGENT_BROWSER_COLOR_SCHEME=dark agent-browser open https://example.com
-
-# Or set during session (persists for subsequent commands)
-agent-browser set media dark
-\`\`\`
-
-### Viewport & Responsive Testing
-
-\`\`\`bash
-# Set a custom viewport size (default is 1280x720)
-agent-browser set viewport 1920 1080
-agent-browser screenshot desktop.png
-
-# Test mobile-width layout
-agent-browser set viewport 375 812
-agent-browser screenshot mobile.png
-
-# Retina/HiDPI: same CSS layout at 2x pixel density
-# Screenshots stay at logical viewport size, but content renders at higher DPI
-agent-browser set viewport 1920 1080 2
-agent-browser screenshot retina.png
-
-# Device emulation (sets viewport + user agent in one step)
-agent-browser set device "iPhone 14"
-agent-browser screenshot device.png
-\`\`\`
-
-The \`scale\` parameter (3rd argument) sets \`window.devicePixelRatio\` without changing CSS layout. Use it when testing retina rendering or capturing higher-resolution screenshots.
-
-### Visual Browser (Debugging)
-
-\`\`\`bash
-agent-browser --headed open https://example.com
-agent-browser highlight @e1 # Highlight element
-agent-browser inspect # Open Chrome DevTools for the active page
-agent-browser record start demo.webm # Record session
-agent-browser profiler start # Start Chrome DevTools profiling
-agent-browser profiler stop trace.json # Stop and save profile (path optional)
-\`\`\`
-
-Use \`AGENT_BROWSER_HEADED=1\` to enable headed mode via environment variable. Browser extensions work in both headed and headless mode.
-
-### Local Files (PDFs, HTML)
-
-\`\`\`bash
-# Open local files with file:// URLs
-agent-browser --allow-file-access open file:///path/to/document.pdf
-agent-browser --allow-file-access open file:///path/to/page.html
-agent-browser screenshot output.png
-\`\`\`
-
-### iOS Simulator (Mobile Safari)
-
-\`\`\`bash
-# List available iOS simulators
-agent-browser device list
-
-# Launch Safari on a specific device
-agent-browser -p ios --device "iPhone 16 Pro" open https://example.com
-
-# Same workflow as desktop - snapshot, interact, re-snapshot
-agent-browser -p ios snapshot -i
-agent-browser -p ios tap @e1 # Tap (alias for click)
-agent-browser -p ios fill @e2 "text"
-agent-browser -p ios swipe up # Mobile-specific gesture
-
-# Take screenshot
-agent-browser -p ios screenshot mobile.png
-
-# Close session (shuts down simulator)
-agent-browser -p ios close
-\`\`\`
-
-**Requirements:** macOS with Xcode, Appium (\`npm install -g appium && appium driver install xcuitest\`)
-
-**Real devices:** Works with physical iOS devices if pre-configured. Use \`--device "<UDID>"\` where UDID is from \`xcrun xctrace list devices\`.
-
-## Security
-
-All security features are opt-in. By default, agent-browser imposes no restrictions on navigation, actions, or output.
-
-### Content Boundaries (Recommended for AI Agents)
-
-Enable \`--content-boundaries\` to wrap page-sourced output in markers that help LLMs distinguish tool output from untrusted page content:
-
-\`\`\`bash
-export AGENT_BROWSER_CONTENT_BOUNDARIES=1
-agent-browser snapshot
-# Output:
-# --- AGENT_BROWSER_PAGE_CONTENT nonce=<hex> origin=https://example.com ---
-# [accessibility tree]
-# --- END_AGENT_BROWSER_PAGE_CONTENT nonce=<hex> ---
-\`\`\`
-
-### Domain Allowlist
-
-Restrict navigation to trusted domains. Wildcards like \`*.example.com\` also match the bare domain \`example.com\`. Sub-resource requests, WebSocket, and EventSource connections to non-allowed domains are also blocked. Include CDN domains your target pages depend on:
-
-\`\`\`bash
-export AGENT_BROWSER_ALLOWED_DOMAINS="example.com,*.example.com"
-agent-browser open https://example.com # OK
-agent-browser open https://malicious.com # Blocked
-\`\`\`
-
-### Action Policy
-
-Use a policy file to gate destructive actions:
-
-\`\`\`bash
-export AGENT_BROWSER_ACTION_POLICY=./policy.json
-\`\`\`
-
-Example \`policy.json\`:
-
-\`\`\`json
-{ "default": "deny", "allow": ["navigate", "snapshot", "click", "scroll", "wait", "get"] }
-\`\`\`
-
-Auth vault operations (\`auth login\`, etc.) bypass action policy but domain allowlist still applies.
-
-### Output Limits
-
-Prevent context flooding from large pages:
-
-\`\`\`bash
-export AGENT_BROWSER_MAX_OUTPUT=50000
-\`\`\`
-
-## Diffing (Verifying Changes)
-
-Use \`diff snapshot\` after performing an action to verify it had the intended effect. This compares the current accessibility tree against the last snapshot taken in the session.
-
-\`\`\`bash
-# Typical workflow: snapshot -> action -> diff
-agent-browser snapshot -i # Take baseline snapshot
-agent-browser click @e2 # Perform action
-agent-browser diff snapshot # See what changed (auto-compares to last snapshot)
-\`\`\`
-
-For visual regression testing or monitoring:
-
-\`\`\`bash
-# Save a baseline screenshot, then compare later
-agent-browser screenshot baseline.png
-# ... time passes or changes are made ...
-agent-browser diff screenshot --baseline baseline.png
-
-# Compare staging vs production
-agent-browser diff url https://staging.example.com https://prod.example.com --screenshot
-\`\`\`
-
-\`diff snapshot\` output uses \`+\` for additions and \`-\` for removals, similar to git diff. \`diff screenshot\` produces a diff image with changed pixels highlighted in red, plus a mismatch percentage.
-
-## Timeouts and Slow Pages
-
-The default timeout is 25 seconds. This can be overridden with the \`AGENT_BROWSER_DEFAULT_TIMEOUT\` environment variable (value in milliseconds).
-
-**Important:** \`open\` already waits for the page \`load\` event before returning. In most cases, no additional wait is needed before taking a snapshot or screenshot. Only add an explicit wait when content loads asynchronously after the initial page load.
-
-\`\`\`bash
-# Wait for a specific element to appear (preferred for dynamic content)
-agent-browser wait "#content"
-agent-browser wait @e1
-
-# Wait a fixed duration (good default for slow SPAs)
-agent-browser wait 2000
-
-# Wait for a specific URL pattern (useful after redirects)
-agent-browser wait --url "**/dashboard"
-
-# Wait for text to appear on the page
-agent-browser wait --text "Results loaded"
-
-# Wait for a JavaScript condition
-agent-browser wait --fn "document.querySelectorAll('.item').length > 0"
-\`\`\`
-
-**Avoid \`wait --load networkidle\`** unless you are certain the site has no persistent network activity. Ad-heavy sites, sites with analytics/tracking, and sites with websockets will cause \`networkidle\` to hang indefinitely. Prefer \`wait 2000\` or \`wait <selector>\` instead.
-
-## JavaScript Dialogs (alert / confirm / prompt)
-
-When a page opens a JavaScript dialog (\`alert()\`, \`confirm()\`, or \`prompt()\`), it blocks all other browser commands (snapshot, screenshot, click, etc.) until the dialog is dismissed. If commands start timing out unexpectedly, check for a pending dialog:
-
-\`\`\`bash
-# Check if a dialog is blocking
-agent-browser dialog status
-
-# Accept the dialog (dismiss the alert / click OK)
-agent-browser dialog accept
-
-# Accept a prompt dialog with input text
-agent-browser dialog accept "my input"
-
-# Dismiss the dialog (click Cancel)
-agent-browser dialog dismiss
-\`\`\`
-
-When a dialog is pending, all command responses include a \`warning\` field indicating the dialog type and message. In \`--json\` mode this appears as a \`"warning"\` key in the response object.
-
-## Session Management and Cleanup
-
-When running multiple agents or automations concurrently, always use named sessions to avoid conflicts:
-
-\`\`\`bash
-# Each agent gets its own isolated session
-agent-browser --session agent1 open site-a.com
-agent-browser --session agent2 open site-b.com
-
-# Check active sessions
-agent-browser session list
-\`\`\`
-
-Always close your browser session when done to avoid leaked processes:
-
-\`\`\`bash
-agent-browser close # Close default session
-agent-browser --session agent1 close # Close specific session
-agent-browser close --all # Close all active sessions
-\`\`\`
-
-If a previous session was not closed properly, the daemon may still be running. Use \`agent-browser close\` to clean it up, or \`agent-browser close --all\` to shut down every session at once.
-
-To auto-shutdown the daemon after a period of inactivity (useful for ephemeral/CI environments):
-
-\`\`\`bash
-AGENT_BROWSER_IDLE_TIMEOUT_MS=60000 agent-browser open example.com
-\`\`\`
-
-## Ref Lifecycle (Important)
-
-Refs (\`@e1\`, \`@e2\`, etc.) are invalidated when the page changes. Always re-snapshot after:
-
-- Clicking links or buttons that navigate
-- Form submissions
-- Dynamic content loading (dropdowns, modals)
-
-\`\`\`bash
-agent-browser click @e5 # Navigates to new page
-agent-browser snapshot -i # MUST re-snapshot
-agent-browser click @e1 # Use new refs
-\`\`\`
-
-## Annotated Screenshots (Vision Mode)
-
-Use \`--annotate\` to take a screenshot with numbered labels overlaid on interactive elements. Each label \`[N]\` maps to ref \`@eN\`. This also caches refs, so you can interact with elements immediately without a separate snapshot.
-
-\`\`\`bash
-agent-browser screenshot --annotate
-# Output includes the image path and a legend:
-# [1] @e1 button "Submit"
-# [2] @e2 link "Home"
-# [3] @e3 textbox "Email"
-agent-browser click @e2 # Click using ref from annotated screenshot
-\`\`\`
-
-Use annotated screenshots when:
-
-- The page has unlabeled icon buttons or visual-only elements
-- You need to verify visual layout or styling
-- Canvas or chart elements are present (invisible to text snapshots)
-- You need spatial reasoning about element positions
-
-## Semantic Locators (Alternative to Refs)
-
-When refs are unavailable or unreliable, use semantic locators:
-
-\`\`\`bash
-agent-browser find text "Sign In" click
-agent-browser find label "Email" fill "[email protected]"
-agent-browser find role button click --name "Submit"
-agent-browser find placeholder "Search" type "query"
-agent-browser find testid "submit-btn" click
-\`\`\`
-
-## JavaScript Evaluation (eval)
-
-Use \`eval\` to run JavaScript in the browser context. **Shell quoting can corrupt complex expressions** -- use \`--stdin\` or \`-b\` to avoid issues.
-
-\`\`\`bash
-# Simple expressions work with regular quoting
-agent-browser eval 'document.title'
-agent-browser eval 'document.querySelectorAll("img").length'
-
-# Complex JS: use --stdin with heredoc (RECOMMENDED)
-agent-browser eval --stdin <<'EVALEOF'
-JSON.stringify(
- Array.from(document.querySelectorAll("img"))
- .filter(i => !i.alt)
- .map(i => ({ src: i.src.split("/").pop(), width: i.width }))
-)
-EVALEOF
-
-# Alternative: base64 encoding (avoids all shell escaping issues)
-agent-browser eval -b "$(echo -n 'Array.from(document.querySelectorAll("a")).map(a => a.href)' | base64)"
-\`\`\`
-
-**Why this matters:** When the shell processes your command, inner double quotes, \`!\` characters (history expansion), backticks, and \`$()\` can all corrupt the JavaScript before it reaches agent-browser. The \`--stdin\` and \`-b\` flags bypass shell interpretation entirely.
-
-**Rules of thumb:**
-
-- Single-line, no nested quotes -> regular \`eval 'expression'\` with single quotes is fine
-- Nested quotes, arrow functions, template literals, or multiline -> use \`eval --stdin <<'EVALEOF'\`
-- Programmatic/generated scripts -> use \`eval -b\` with base64
-
-## Configuration File
-
-Create \`agent-browser.json\` in the project root for persistent settings:
-
-\`\`\`json
-{
- "headed": true,
- "proxy": "http://localhost:8080",
- "profile": "./browser-data"
-}
-\`\`\`
-
-Priority (lowest to highest): \`~/.agent-browser/config.json\` < \`./agent-browser.json\` < env vars < CLI flags. Use \`--config <path>\` or \`AGENT_BROWSER_CONFIG\` env var for a custom config file (exits with error if missing/invalid). All CLI options map to camelCase keys (e.g., \`--executable-path\` -> \`"executablePath"\`). Boolean flags accept \`true\`/\`false\` values (e.g., \`--headed false\` overrides config). Extensions from user and project configs are merged, not replaced.
-
-## Deep-Dive Documentation
-
-Extended references (commands, snapshot-refs, sessions, authentication, video, profiling, proxy): https://github.com/vercel-labs/agent-browser/tree/main/skills/agent-browser/references
-
-## Cloud Providers
-
-Use \`-p <provider>\` (or \`AGENT_BROWSER_PROVIDER\`) to run against a cloud browser instead of launching a local Chrome instance. Supported providers: \`agentcore\`, \`browserbase\`, \`browserless\`, \`browseruse\`, \`kernel\`.
-
-### AgentCore (AWS Bedrock)
-
-\`\`\`bash
-# Credentials auto-resolved from env vars or AWS CLI (SSO, IAM roles, etc.)
-agent-browser -p agentcore open https://example.com
-
-# With persistent browser profile
-AGENTCORE_PROFILE_ID=my-profile agent-browser -p agentcore open https://example.com
-
-# With explicit region
-AGENTCORE_REGION=eu-west-1 agent-browser -p agentcore open https://example.com
-\`\`\`
-
-Set \`AWS_PROFILE\` to select a named AWS profile.
-
-## Browser Engine Selection
-
-Use \`--engine\` to choose a local browser engine. The default is \`chrome\`.
-
-\`\`\`bash
-# Use Lightpanda (fast headless browser, requires separate install)
-agent-browser --engine lightpanda open example.com
-
-# Via environment variable
-export AGENT_BROWSER_ENGINE=lightpanda
-agent-browser open example.com
-
-# With custom binary path
-agent-browser --engine lightpanda --executable-path /path/to/lightpanda open example.com
-\`\`\`
-
-Supported engines:
-- \`chrome\` (default) -- Chrome/Chromium via CDP
-- \`lightpanda\` -- Lightpanda headless browser via CDP (10x faster, 10x less memory than Chrome)
-
-Lightpanda does not support \`--extension\`, \`--profile\`, \`--state\`, or \`--allow-file-access\`. Install Lightpanda from https://lightpanda.io/docs/open-source/installation.
-
-## Observability Dashboard
-
-The dashboard is a standalone background server that shows live browser viewports, command activity, and console output for all sessions.
-
-\`\`\`bash
-# Start the dashboard server (background, port 4848)
-agent-browser dashboard start
-
-# All sessions are automatically visible in the dashboard
-agent-browser open example.com
-
-# Stop the dashboard
-agent-browser dashboard stop
-\`\`\`
-
-The dashboard runs independently of browser sessions on port 4848 (configurable with \`--port\`). All sessions automatically stream to the dashboard. Sessions can also be created from the dashboard UI with local engines or cloud providers.
-
-### Dashboard AI Chat
-
-The dashboard has an optional AI chat tab powered by the Vercel AI Gateway. Enable it by setting:
-
-\`\`\`bash
-export AI_GATEWAY_API_KEY=gw_your_key_here
-export AI_GATEWAY_MODEL=anthropic/claude-sonnet-4.6 # optional default
-export AI_GATEWAY_URL=https://ai-gateway.vercel.sh # optional default
-\`\`\`
-
-The Chat tab is always visible in the dashboard. Set \`AI_GATEWAY_API_KEY\` to enable AI responses.
-
-## Ready-to-Use Templates
-
-Example scripts in the upstream repo: https://github.com/vercel-labs/agent-browser/tree/main/skills/agent-browser/templates
-
+Refs become **stale on every page change** (click that navigates, form submit, dynamic re-render, dialog open). Always re-snapshot before the next ref interaction.
-# Execution Rules in This Runtime
+## Discovering everything else
-- Run all agent-browser commands via \`execScript\` with \`runInClient: true\` because it is a local CLI.
-- Prefer \`--json\` output when structured parsing is needed.
-- Always close sessions when done: \`agent-browser close\`, \`agent-browser close --all\`, or \`agent-browser --session <name> close\`.
-- If a task stalls, use explicit \`wait\` commands instead of blind retries.
-- Run \`snapshot -i\` alone when you must read refs from output; then use \`agent-browser batch\` or \`&&\` for the remaining steps (see **Batch Execution** above).
-</agent_browser_guides>
-`;
+Run \`agent-browser --help\` for the full command list, then \`agent-browser <subcommand> --help\` for any subcommand whose flags you're unsure about. The CLI also ships specialized skills (\`agent-browser skills list\`, \`agent-browser skills get <name>\`) covering Electron apps, Slack, dogfooding, Vercel Sandbox, and AWS Bedrock AgentCore β€” load one only when the task falls outside ordinary web pages.
+</agent_browser_guides>`;
diff --git a/packages/builtin-skills/src/agent-browser/index.ts b/packages/builtin-skills/src/agent-browser/index.ts
index 2283b8210cc..c11322796b3 100644
--- a/packages/builtin-skills/src/agent-browser/index.ts
+++ b/packages/builtin-skills/src/agent-browser/index.ts
@@ -8,7 +8,7 @@ export const AgentBrowserSkill: BuiltinSkill = {
avatar: `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDQ4IDQ4Ij48ZyBmaWxsPSJub25lIj48cGF0aCBmaWxsPSIjOGZiZmZhIiBkPSJNMjQgNDYuNWMtNy40MDEgMC0xMi41OTMtLjI3OC0xNS44NjQtLjU0NGMtMy4yODgtLjI2Ny01LjgyNS0yLjgwNC02LjA5Mi02LjA5MkMxLjc3OCAzNi41OTMgMS41IDMxLjQwMSAxLjUgMjRzLjI3OC0xMi41OTMuNTQ0LTE1Ljg2NGMuMjY3LTMuMjg4IDIuODA0LTUuODI1IDYuMDkyLTYuMDkyQzExLjQwNyAxLjc3OCAxNi41OTkgMS41IDI0IDEuNXMxMi41OTMuMjc4IDE1Ljg2NC41NDRjMy4yODguMjY3IDUuODI1IDIuODA0IDYuMDkyIDYuMDkyYy4yNjYgMy4yNzEuNTQ0IDguNDYzLjU0NCAxNS44NjRzLS4yNzggMTIuNTkzLS41NDQgMTUuODY0Yy0uMjY3IDMuMjg4LTIuODA0IDUuODI1LTYuMDkyIDYuMDkyYy0zLjI3MS4yNjYtOC40NjMuNTQ0LTE1Ljg2NC41NDQiLz48cGF0aCBmaWxsPSIjMjg1OWM1IiBkPSJNNDYuMjYyIDEzSDEuNzM3Yy4wOTItMS45NC4yLTMuNTU2LjMwNy00Ljg2NGMuMjY3LTMuMjg4IDIuODAzLTUuODI1IDYuMDkxLTYuMDkyQzExLjQwNyAxLjc3OCAxNi41OTggMS41IDI0IDEuNWM3LjQwMSAwIDEyLjU5Mi4yNzggMTUuODY0LjU0NGMzLjI4OC4yNjcgNS44MjUgMi44MDQgNi4wOTIgNi4wOTJjLjEwNiAxLjMwOC4yMTQgMi45MjMuMzA2IDQuODY0Ii8+PHBhdGggZmlsbD0iIzhmYmZmYSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNOCA3LjVBMS41IDEuNSAwIDAgMSA5LjUgNmgyYTEuNSAxLjUgMCAwIDEgMCAzaC0yQTEuNSAxLjUgMCAwIDEgOCA3LjVNMTcuNSA2YTEuNSAxLjUgMCAwIDAgMCAzaDJhMS41IDEuNSAwIDAgMCAwLTN6IiBjbGlwLXJ1bGU9ImV2ZW5vZGQiLz48cGF0aCBmaWxsPSIjMjg1OWM1IiBkPSJNMTMuMTIxIDM4LjIzNGMyLjQ4OS0xLjI2NiA1LjExMS0yLjY3OCA3LjI3NS00LjU3MmMuOTY3LS44NDYgMi4xMDQtMi4wNjcgMi4xMDQtMy42NjNzLTEuMTM3LTIuODE3LTIuMTA0LTMuNjYyYy0yLjE2NC0xLjg5NC00Ljc4Ny0zLjMwNy03LjI3NS00LjU3M2EyLjQ5NiAyLjQ5NiAwIDAgMC0zLjM1NyAxLjExN2EyLjUwNSAyLjUwNSAwIDAgMCAxLjExNSAzLjM1MmwuMjQ4LjEyN2MyLjA1NCAxLjA0NSA0LjIxOCAyLjE0NyA1Ljg3NiAzLjY0Yy0xLjY1OCAxLjQ5Mi0zLjgyMSAyLjU5My01Ljg3NSAzLjYzOWwtLjI1LjEyN2EyLjUwNSAyLjUwNSAwIDAgMC0xLjExNCAzLjM1MWEyLjQ5NiAyLjQ5NiAwIDAgMCAzLjM1NyAxLjExN00yNiAzMy41YTIuNSAyLjUgMCAwIDAgMCA1aDEwYTIuNSAyLjUgMCAwIDAgMC01eiIvPjwvZz48L3N2Zz4=`,
content: systemPrompt,
description:
- 'Browser automation CLI for AI agents (agent-browser v0.20.1). Use when tasks involve website or Electron interaction such as navigation, form filling, clicking, screenshot capture, scraping data, login flows, and end-to-end app testing.',
+ 'Browser automation CLI for AI agents (agent-browser v0.31.1). Use when tasks involve website or Electron interaction such as navigation, form filling, clicking, screenshot capture, scraping data, login flows, and end-to-end app testing.',
identifier: AgentBrowserIdentifier,
name: 'Agent Browser',
source: 'builtin',
diff --git a/packages/electron-client-ipc/src/types/toolDetector.ts b/packages/electron-client-ipc/src/types/binary.ts
similarity index 73%
rename from packages/electron-client-ipc/src/types/toolDetector.ts
rename to packages/electron-client-ipc/src/types/binary.ts
index 438aba07401..1c5562bd8c6 100644
--- a/packages/electron-client-ipc/src/types/toolDetector.ts
+++ b/packages/electron-client-ipc/src/types/binary.ts
@@ -1,7 +1,7 @@
/**
- * Tool detection status
+ * Status of a registered binary
*/
-export interface ToolStatus {
+export interface BinaryStatus {
available: boolean;
error?: string;
lastChecked?: Date;
@@ -10,14 +10,14 @@ export interface ToolStatus {
}
/**
- * Tool categories
+ * Binary categories
*/
-export type ToolCategory = 'content-search' | 'custom' | 'file-search' | 'system';
+export type BinaryCategory = 'content-search' | 'custom' | 'file-search' | 'system';
/**
- * Tool info for display
+ * Binary info for display
*/
-export interface ToolInfo {
+export interface BinaryInfo {
description?: string;
name: string;
priority?: number;
diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.ts
index 510f9b40361..767a4cce430 100644
--- a/packages/electron-client-ipc/src/types/index.ts
+++ b/packages/electron-client-ipc/src/types/index.ts
@@ -1,3 +1,4 @@
+export * from './binary';
export * from './dataSync';
export * from './git';
export * from './heterogeneousAgent';
@@ -11,7 +12,6 @@ export * from './route';
export * from './screenCapture';
export * from './shortcut';
export * from './system';
-export * from './toolDetector';
export * from './topicPopup';
export * from './tray';
export * from './update';
diff --git a/packages/local-file-shell/src/toolDetector.ts b/packages/local-file-shell/src/toolDetector.ts
index 8953ceccaea..cdaf92d6182 100644
--- a/packages/local-file-shell/src/toolDetector.ts
+++ b/packages/local-file-shell/src/toolDetector.ts
@@ -6,7 +6,7 @@ export type ToolCategory = 'content-search' | 'file-search';
/**
* Minimal contract the search modules need from a tool detector. Desktop
- * injects its full ToolDetectorManager (which also handles registration and
+ * injects its full BinaryManager (which also handles registration and
* caching); CLI / sandbox can leave it unset, in which case each impl falls
* back to its own `which`-based detection.
*/
diff --git a/src/features/Recommendations/actions/types.ts b/src/features/Recommendations/actions/types.ts
index faa7e9242ae..dc921b25403 100644
--- a/src/features/Recommendations/actions/types.ts
+++ b/src/features/Recommendations/actions/types.ts
@@ -1,4 +1,4 @@
-import type { HeterogeneousCliAgentType, ToolStatus } from '@lobechat/electron-client-ipc';
+import type { BinaryStatus, HeterogeneousCliAgentType } from '@lobechat/electron-client-ipc';
import type { HeterogeneousAgentClientConfig } from '@lobechat/heterogeneous-agents/client';
import type { SidebarAgentItem } from '@lobechat/types';
import type { TFunction } from 'i18next';
@@ -6,7 +6,7 @@ import type { ReactNode } from 'react';
import type { CreateHeteroAgentOptions } from '@/hooks/useCreateHeteroAgent';
-export type HeteroDetectionMap = Partial<Record<HeterogeneousCliAgentType, ToolStatus>>;
+export type HeteroDetectionMap = Partial<Record<HeterogeneousCliAgentType, BinaryStatus>>;
export interface ActionContext {
agents: SidebarAgentItem[];
diff --git a/src/features/Recommendations/hooks/useHeteroDetections.ts b/src/features/Recommendations/hooks/useHeteroDetections.ts
index 7b1ad53fda7..757c13e8dec 100644
--- a/src/features/Recommendations/hooks/useHeteroDetections.ts
+++ b/src/features/Recommendations/hooks/useHeteroDetections.ts
@@ -1,10 +1,10 @@
import { isDesktop } from '@lobechat/const';
-import type { ToolStatus } from '@lobechat/electron-client-ipc';
+import type { BinaryStatus } from '@lobechat/electron-client-ipc';
import { HETEROGENEOUS_AGENT_CLIENT_CONFIGS } from '@lobechat/heterogeneous-agents/client';
import useSWR from 'swr';
import { recommendationsKeys } from '@/libs/swr/keys';
-import { toolDetectorService } from '@/services/electron/toolDetector';
+import { binaryService } from '@/services/electron/binary';
import type { HeteroDetectionMap } from '../actions/types';
@@ -22,14 +22,14 @@ export const useHeteroDetections = (): HeteroDetectionMap => {
const entries = await Promise.all(
HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map(async (config) => {
try {
- const status = await toolDetectorService.detectHeterogeneousAgentCommand({
+ const status = await binaryService.detectHeterogeneousAgentCommand({
agentType: config.type,
command: config.command,
});
return [config.type, status] as const;
} catch (error) {
console.error(`[recommendations] hetero detection failed for ${config.type}:`, error);
- const fallback: ToolStatus = { available: false, error: String(error) };
+ const fallback: BinaryStatus = { available: false, error: String(error) };
return [config.type, fallback] as const;
}
}),
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
index 08c7bf0cf9c..0315be4dac2 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
@@ -126,8 +126,8 @@ vi.mock('@/features/Electron/HeterogeneousAgent/StatusGuide', () => ({
),
}));
-vi.mock('@/services/electron/toolDetector', () => ({
- toolDetectorService: {
+vi.mock('@/services/electron/binary', () => ({
+ binaryService: {
detectHeterogeneousAgentCommand,
getClaudeAuthStatus,
},
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
index 20da3bf5d58..bc8d8e3c1df 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
@@ -1,7 +1,7 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import { type ClaudeAuthStatus, type ToolStatus } from '@lobechat/electron-client-ipc';
+import { type BinaryStatus, type ClaudeAuthStatus } from '@lobechat/electron-client-ipc';
import {
getHeterogeneousAgentClientConfig,
isRemoteHeterogeneousType,
@@ -16,7 +16,7 @@ import { useTranslation } from 'react-i18next';
import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
-import { toolDetectorService } from '@/services/electron/toolDetector';
+import { binaryService } from '@/services/electron/binary';
const COMMAND_LINE_HEIGHT = 28;
@@ -222,7 +222,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
const defaultCommand = providerConfig?.command || '';
const resolvedCommand = provider.command?.trim() || defaultCommand;
const isUsingCustomCommand = resolvedCommand !== defaultCommand;
- const [status, setStatus] = useState<ToolStatus | undefined>();
+ const [status, setStatus] = useState<BinaryStatus | undefined>();
const [auth, setAuth] = useState<ClaudeAuthStatus | null>(null);
const [commandInput, setCommandInput] = useState(resolvedCommand);
const [detecting, setDetecting] = useState(true);
@@ -245,7 +245,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
}
try {
- const result = await toolDetectorService.getClaudeAuthStatus(resolvedCommand);
+ const result = await binaryService.getClaudeAuthStatus(resolvedCommand);
setAuth(result);
} catch (error) {
console.warn('[HeterogeneousAgentStatusCard] Failed to get Claude auth status:', error);
@@ -262,7 +262,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
setDetecting(true);
try {
- const result = await toolDetectorService.detectHeterogeneousAgentCommand({
+ const result = await binaryService.detectHeterogeneousAgentCommand({
agentType: provider.type,
command: resolvedCommand,
});
diff --git a/src/routes/(main)/settings/system-tools/features/ToolDetectorSection.tsx b/src/routes/(main)/settings/system-tools/features/ToolDetectorSection.tsx
index 4248ae361e5..cef5cbe96ee 100644
--- a/src/routes/(main)/settings/system-tools/features/ToolDetectorSection.tsx
+++ b/src/routes/(main)/settings/system-tools/features/ToolDetectorSection.tsx
@@ -1,6 +1,6 @@
'use client';
-import { type ToolStatus } from '@lobechat/electron-client-ipc';
+import { type BinaryStatus } from '@lobechat/electron-client-ipc';
import { type FormGroupItemType } from '@lobehub/ui';
import { Button, CopyButton, Flexbox, Form, Icon, Tag, Text, Tooltip } from '@lobehub/ui';
import { CheckCircle2, Loader2Icon, RefreshCw, XCircle } from 'lucide-react';
@@ -8,7 +8,7 @@ import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FORM_STYLE } from '@/const/layoutTokens';
-import { toolDetectorService } from '@/services/electron/toolDetector';
+import { binaryService } from '@/services/electron/binary';
/**
* Predefined tool configurations by category
@@ -70,7 +70,7 @@ const TOOL_CATEGORIES = {
interface ToolStatusDisplayProps {
isDetecting?: boolean;
- status?: ToolStatus;
+ status?: BinaryStatus;
}
const ToolStatusDisplay = memo<ToolStatusDisplayProps>(({ status, isDetecting }) => {
@@ -125,13 +125,13 @@ const ToolStatusDisplay = memo<ToolStatusDisplayProps>(({ status, isDetecting })
const ToolDetectorSection = memo(() => {
const { t } = useTranslation('setting');
- const [toolStatuses, setToolStatuses] = useState<Record<string, ToolStatus>>({});
+ const [toolStatuses, setToolStatuses] = useState<Record<string, BinaryStatus>>({});
const [detecting, setDetecting] = useState(true);
const detectTools = useCallback(async (force = false) => {
try {
setDetecting(true);
- const statuses = await toolDetectorService.detectAllTools(force);
+ const statuses = await binaryService.detectAll(force);
setToolStatuses(statuses);
} catch (error) {
console.error('Failed to detect tools:', error);
diff --git a/src/services/electron/binary.ts b/src/services/electron/binary.ts
new file mode 100644
index 00000000000..cbe2c78c52a
--- /dev/null
+++ b/src/services/electron/binary.ts
@@ -0,0 +1,99 @@
+import {
+ type BinaryCategory,
+ type BinaryInfo,
+ type BinaryStatus,
+ type ClaudeAuthStatus,
+ type DetectHeterogeneousAgentCommandParams,
+} from '@lobechat/electron-client-ipc';
+
+import { ensureElectronIpc } from '@/utils/electron/ipc';
+
+class BinaryService {
+ /**
+ * Detect a single binary
+ */
+ detect = async (name: string, force = false): Promise<BinaryStatus> => {
+ return ensureElectronIpc().binary.detect(name, force);
+ };
+
+ detectHeterogeneousAgentCommand = async (
+ params: DetectHeterogeneousAgentCommandParams,
+ ): Promise<BinaryStatus> => {
+ return ensureElectronIpc().binary.detectHeterogeneousAgentCommand(params);
+ };
+
+ /**
+ * Detect all registered binaries
+ */
+ detectAll = async (force = false): Promise<Record<string, BinaryStatus>> => {
+ return ensureElectronIpc().binary.detectAll(force);
+ };
+
+ /**
+ * Detect all binaries in a category
+ */
+ detectCategory = async (
+ category: BinaryCategory,
+ force = false,
+ ): Promise<Record<string, BinaryStatus>> => {
+ return ensureElectronIpc().binary.detectCategory(category, force);
+ };
+
+ /**
+ * Get the best available binary in a category
+ */
+ getBestTool = async (category: BinaryCategory): Promise<string | null> => {
+ return ensureElectronIpc().binary.getBestTool(category);
+ };
+
+ /**
+ * Get cached status for a binary (no detection)
+ */
+ getStatus = (name: string): BinaryStatus | null => {
+ return ensureElectronIpc().binary.getStatus(name);
+ };
+
+ /**
+ * Get all cached statuses (no detection)
+ */
+ getAllStatus = (): Record<string, BinaryStatus> => {
+ return ensureElectronIpc().binary.getAllStatus();
+ };
+
+ /**
+ * Clear binary status cache
+ */
+ clearCache = (name?: string): void => {
+ ensureElectronIpc().binary.clearCache(name);
+ };
+
+ /**
+ * Get list of registered binary names
+ */
+ getRegistered = (): string[] => {
+ return ensureElectronIpc().binary.getRegistered();
+ };
+
+ /**
+ * Get all categories
+ */
+ getCategories = (): BinaryCategory[] => {
+ return ensureElectronIpc().binary.getCategories();
+ };
+
+ /**
+ * Get binaries in a category with their info
+ */
+ getInCategory = (category: BinaryCategory): BinaryInfo[] => {
+ return ensureElectronIpc().binary.getInCategory(category);
+ };
+
+ /**
+ * Get Claude Code CLI auth/account status
+ */
+ getClaudeAuthStatus = async (command = 'claude'): Promise<ClaudeAuthStatus | null> => {
+ return ensureElectronIpc().binary.getClaudeAuthStatus(command);
+ };
+}
+
+export const binaryService = new BinaryService();
diff --git a/src/services/electron/toolDetector.ts b/src/services/electron/toolDetector.ts
deleted file mode 100644
index cda5088277a..00000000000
--- a/src/services/electron/toolDetector.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import {
- type ClaudeAuthStatus,
- type DetectHeterogeneousAgentCommandParams,
- type ToolCategory,
- type ToolInfo,
- type ToolStatus,
-} from '@lobechat/electron-client-ipc';
-
-import { ensureElectronIpc } from '@/utils/electron/ipc';
-
-class ToolDetectorService {
- /**
- * Detect a single tool
- */
- detectTool = async (name: string, force = false): Promise<ToolStatus> => {
- return ensureElectronIpc().toolDetector.detectTool(name, force);
- };
-
- detectHeterogeneousAgentCommand = async (
- params: DetectHeterogeneousAgentCommandParams,
- ): Promise<ToolStatus> => {
- return ensureElectronIpc().toolDetector.detectHeterogeneousAgentCommand(params);
- };
-
- /**
- * Detect all registered tools
- */
- detectAllTools = async (force = false): Promise<Record<string, ToolStatus>> => {
- return ensureElectronIpc().toolDetector.detectAllTools(force);
- };
-
- /**
- * Detect all tools in a category
- */
- detectCategory = async (
- category: ToolCategory,
- force = false,
- ): Promise<Record<string, ToolStatus>> => {
- return ensureElectronIpc().toolDetector.detectCategory(category, force);
- };
-
- /**
- * Get the best available tool in a category
- */
- getBestTool = async (category: ToolCategory): Promise<string | null> => {
- return ensureElectronIpc().toolDetector.getBestTool(category);
- };
-
- /**
- * Get cached status for a tool (no detection)
- */
- getToolStatus = (name: string): ToolStatus | null => {
- return ensureElectronIpc().toolDetector.getToolStatus(name);
- };
-
- /**
- * Get all cached statuses (no detection)
- */
- getAllToolStatus = (): Record<string, ToolStatus> => {
- return ensureElectronIpc().toolDetector.getAllToolStatus();
- };
-
- /**
- * Clear tool status cache
- */
- clearToolCache = (name?: string): void => {
- ensureElectronIpc().toolDetector.clearToolCache(name);
- };
-
- /**
- * Get list of registered tools
- */
- getRegisteredTools = (): string[] => {
- return ensureElectronIpc().toolDetector.getRegisteredTools();
- };
-
- /**
- * Get all categories
- */
- getCategories = (): ToolCategory[] => {
- return ensureElectronIpc().toolDetector.getCategories();
- };
-
- /**
- * Get tools in a category with their info
- */
- getToolsInCategory = (category: ToolCategory): ToolInfo[] => {
- return ensureElectronIpc().toolDetector.getToolsInCategory(category);
- };
-
- /**
- * Get Claude Code CLI auth/account status
- */
- getClaudeAuthStatus = async (command = 'claude'): Promise<ClaudeAuthStatus | null> => {
- return ensureElectronIpc().toolDetector.getClaudeAuthStatus(command);
- };
-}
-
-export const toolDetectorService = new ToolDetectorService();