🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(cli): tool worker isolation (#16200)
Rylan Cai2aabda528162
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex 026b543912f..8ef7fee141c 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -35,6 +35,7 @@ import { registerUpdateCommand } from './commands/update';import { registerUserCommand } from './commands/user';import { registerVerifyCommand } from './commands/verify';import { cliVersion } from './pkg';+import { executeToolCall } from './tools';export function createProgram() {const program = new Command();@@ -44,6 +45,27 @@ export function createProgram() {.description('LobeHub CLI - manage and connect to LobeHub services').version(cliVersion);+ const internalToolWorker = program+ .command('tool-worker')+ .description('Internal command for isolated tool execution')+ .requiredOption('--api <name>')+ .requiredOption('--args-b64 <value>')+ .option('--timeout <ms>')+ .action(async (options: { api: string; argsB64: string; timeout?: string }) => {+ const argsStr = Buffer.from(options.argsB64, 'base64').toString('utf8');+ const parsedTimeout =+ options.timeout && options.timeout.trim()+ ? Number.parseInt(options.timeout, 10)+ : undefined;+ const result = await executeToolCall(+ options.api,+ argsStr,+ Number.isFinite(parsedTimeout) ? parsedTimeout : undefined,+ );+ process.stdout.write(JSON.stringify(result));+ });+ internalToolWorker.helpInformation = () => '';+registerLoginCommand(program);registerLogoutCommand(program);registerCompletionCommand(program);diff --git a/apps/cli/src/tools/index.test.ts b/apps/cli/src/tools/index.test.tsindex 1b54301bda3..affa7ac85a1 100644--- a/apps/cli/src/tools/index.test.ts+++ b/apps/cli/src/tools/index.test.ts@@ -7,6 +7,7 @@ import { ShellProcessManager } from '@lobechat/local-file-shell';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { executeToolCall } from './index';+import * as isolatedWorker from './isolatedWorker';vi.mock('../utils/logger', () => ({log: {@@ -77,24 +78,34 @@ describe('executeToolCall', () => {});it('should dispatch listFiles', async () => {- await writeFile(path.join(tmpDir, 'a.txt'), 'a');+ const workerResult = { content: 'list result', state: { totalCount: 1 }, success: true };+ const spy = vi+ .spyOn(isolatedWorker, 'executeToolCallInWorker')+ .mockResolvedValueOnce(workerResult);const result = await executeToolCall('listFiles', JSON.stringify({ path: tmpDir }));- expect(result.success).toBe(true);- expect((result.state as { totalCount: number }).totalCount).toBeGreaterThan(0);+ expect(result).toEqual(workerResult);+ expect(spy).toHaveBeenCalledWith('listFiles', JSON.stringify({ path: tmpDir }), undefined);});it('should dispatch globFiles', async () => {- await writeFile(path.join(tmpDir, 'test.ts'), 'code');+ const workerResult = { content: 'glob result', state: { files: ['test.ts'] }, success: true };+ const spy = vi+ .spyOn(isolatedWorker, 'executeToolCallInWorker')+ .mockResolvedValueOnce(workerResult);const result = await executeToolCall('globFiles',JSON.stringify({ cwd: tmpDir, pattern: '*.ts' }),);- expect(result.success).toBe(true);- expect((result.state as { files: string[] }).files).toContain('test.ts');+ expect(result).toEqual(workerResult);+ expect(spy).toHaveBeenCalledWith(+ 'globFiles',+ JSON.stringify({ cwd: tmpDir, pattern: '*.ts' }),+ undefined,+ );});it('should dispatch editFile', async () => {@@ -141,27 +152,49 @@ describe('executeToolCall', () => {});it('should dispatch grepContent', async () => {- await writeFile(path.join(tmpDir, 'grep.txt'), 'findme here');+ const workerResult = {+ content: 'grep result',+ state: { matches: [{ type: 'match' }] },+ success: true,+ };+ const spy = vi+ .spyOn(isolatedWorker, 'executeToolCallInWorker')+ .mockResolvedValueOnce(workerResult);const result = await executeToolCall('grepContent',JSON.stringify({ cwd: tmpDir, pattern: 'findme' }),);- expect(result.success).toBe(true);- expect(result.state).toBeDefined();+ expect(result).toEqual(workerResult);+ expect(spy).toHaveBeenCalledWith(+ 'grepContent',+ JSON.stringify({ cwd: tmpDir, pattern: 'findme' }),+ undefined,+ );});it('should dispatch searchFiles', async () => {- await writeFile(path.join(tmpDir, 'search_target.txt'), 'found');+ const workerResult = {+ content: 'search result',+ state: { results: [{ path: path.join(tmpDir, 'search_target.txt') }] },+ success: true,+ };+ const spy = vi+ .spyOn(isolatedWorker, 'executeToolCallInWorker')+ .mockResolvedValueOnce(workerResult);const result = await executeToolCall('searchFiles',JSON.stringify({ directory: tmpDir, keywords: 'search_target' }),);- expect(result.success).toBe(true);- expect(result.state).toBeDefined();+ expect(result).toEqual(workerResult);+ expect(spy).toHaveBeenCalledWith(+ 'searchFiles',+ JSON.stringify({ directory: tmpDir, keywords: 'search_target' }),+ undefined,+ );});it('should dispatch getCommandOutput', async () => {diff --git a/apps/cli/src/tools/index.ts b/apps/cli/src/tools/index.tsindex 60d11813141..79d72bd168b 100644--- a/apps/cli/src/tools/index.ts+++ b/apps/cli/src/tools/index.ts@@ -2,6 +2,7 @@ import { log } from '../utils/logger';import { checkPlatformCapability } from './checkPlatformCapability';import { getAgentProfile } from './getAgentProfile';import { cancelHeteroTask, runHeteroTask } from './heteroTask';+import { executeToolCallInWorker, shouldRunInWorker } from './isolatedWorker';import { runLocalSystemTool } from './localSystemRuntime';/**@@ -26,6 +27,8 @@ export async function executeToolCall(state?: unknown;success: boolean;}> {+ if (shouldRunInWorker(apiName)) return executeToolCallInWorker(apiName, argsStr, timeout);+let args: Record<string, any>;try {args = JSON.parse(argsStr);diff --git a/apps/cli/src/tools/isolatedWorker.test.ts b/apps/cli/src/tools/isolatedWorker.test.tsnew file mode 100644index 00000000000..791d58e270b--- /dev/null+++ b/apps/cli/src/tools/isolatedWorker.test.ts@@ -0,0 +1,145 @@+import type { ChildProcessWithoutNullStreams } from 'node:child_process';+import { PassThrough } from 'node:stream';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const spawnMock = vi.fn();++vi.mock('node:child_process', () => ({+ spawn: spawnMock,+}));++describe('executeToolCallInWorker', () => {+ beforeEach(() => {+ spawnMock.mockReset();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ it('should prefer stderr over stdout when reporting worker failure output', async () => {+ spawnMock.mockImplementation(() => {+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const child = {+ kill: vi.fn(),+ on: vi.fn((event: string, handler: (...args: any[]) => void) => {+ if (event === 'close') {+ stdout.write('worker stdout');+ stderr.write('worker stderr');+ stdout.end();+ stderr.end();+ setImmediate(() => handler(1, null));+ }+ return child;+ }),+ stderr,+ stdout,+ } as unknown as ChildProcessWithoutNullStreams;++ return child;+ });++ const { executeToolCallInWorker } = await import('./isolatedWorker');+ const result = await executeToolCallInWorker('searchFiles', '{"keywords":""}');++ expect(result).toEqual({+ content: '',+ error: 'Isolated tool worker failed for searchFiles with exit code 1: worker stderr',+ success: false,+ });+ });++ it('should use No Output when worker exits without stdout or stderr', async () => {+ spawnMock.mockImplementation(() => {+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const child = {+ kill: vi.fn(),+ on: vi.fn((event: string, handler: (...args: any[]) => void) => {+ if (event === 'close') {+ stdout.end();+ stderr.end();+ setImmediate(() => handler(1, null));+ }+ return child;+ }),+ stderr,+ stdout,+ } as unknown as ChildProcessWithoutNullStreams;++ return child;+ });++ const { executeToolCallInWorker } = await import('./isolatedWorker');+ const result = await executeToolCallInWorker('globFiles', '{"pattern":"*.ts"}');++ expect(result).toEqual({+ content: '',+ error: 'Isolated tool worker failed for globFiles with exit code 1: No Output',+ success: false,+ });+ });++ it('should report invalid JSON output from a successful worker exit', async () => {+ spawnMock.mockImplementation(() => {+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const child = {+ kill: vi.fn(),+ on: vi.fn((event: string, handler: (...args: any[]) => void) => {+ if (event === 'close') {+ stdout.write('not-json');+ stdout.end();+ stderr.end();+ setImmediate(() => handler(0, null));+ }+ return child;+ }),+ stderr,+ stdout,+ } as unknown as ChildProcessWithoutNullStreams;++ return child;+ });++ const { executeToolCallInWorker } = await import('./isolatedWorker');+ const result = await executeToolCallInWorker('listFiles', '{"path":"/tmp"}');++ expect(result.success).toBe(false);+ expect(result.error).toContain('Isolated tool worker returned invalid JSON for listFiles:');+ expect(result.error).toContain('Output: not-json');+ });++ it('should timeout and kill the worker when it exceeds the timeout', async () => {+ vi.useFakeTimers();++ const kill = vi.fn();+ spawnMock.mockImplementation(() => {+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const child = {+ kill,+ on: vi.fn(() => child),+ stderr,+ stdout,+ } as unknown as ChildProcessWithoutNullStreams;++ return child;+ });++ const { executeToolCallInWorker } = await import('./isolatedWorker');+ const resultPromise = executeToolCallInWorker('grepContent', '{"pattern":"hello"}', 1000);++ await vi.advanceTimersByTimeAsync(1000);++ await expect(resultPromise).resolves.toEqual({+ content: '',+ error: 'Isolated tool worker timed out for grepContent after 1000ms',+ success: false,+ });+ expect(kill).toHaveBeenCalledWith('SIGKILL');+ });+});diff --git a/apps/cli/src/tools/isolatedWorker.ts b/apps/cli/src/tools/isolatedWorker.tsnew file mode 100644index 00000000000..2feef0fb42b--- /dev/null+++ b/apps/cli/src/tools/isolatedWorker.ts@@ -0,0 +1,131 @@+import * as childProcess from 'node:child_process';++const ISOLATED_TOOL_APIS = new Set(['globFiles', 'grepContent', 'listFiles', 'searchFiles']);+const TOOL_WORKER_ENV = 'LOBEHUB_CLI_TOOL_WORKER';+const DEFAULT_WORKER_TIMEOUT_MS = 30_000;++export const shouldRunInWorker = (apiName: string) =>+ ISOLATED_TOOL_APIS.has(apiName) && process.env[TOOL_WORKER_ENV] !== '1';++type ToolCallResult = {+ content: string;+ error?: string;+ state?: unknown;+ success: boolean;+};++export async function executeToolCallInWorker(+ apiName: string,+ argsStr: string,+ timeout?: number,+): Promise<ToolCallResult> {+ const entrypoint = process.argv[1];+ if (!entrypoint) {+ return {+ content: '',+ error: `CLI entrypoint is unavailable for isolated tool execution: ${apiName}`,+ success: false,+ };+ }++ return new Promise((resolve) => {+ const workerTimeout =+ typeof timeout === 'number' && Number.isFinite(timeout)+ ? Math.min(Math.max(Math.trunc(timeout), 1000), 300_000)+ : DEFAULT_WORKER_TIMEOUT_MS;+ const child = childProcess.spawn(+ process.execPath,+ [+ entrypoint,+ 'tool-worker',+ '--api',+ apiName,+ '--args-b64',+ Buffer.from(argsStr, 'utf8').toString('base64'),+ '--timeout',+ String(timeout ?? ''),+ ],+ {+ env: { ...process.env, [TOOL_WORKER_ENV]: '1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ },+ );++ let stdout = '';+ let stderr = '';+ let settled = false;++ const finish = (result: ToolCallResult) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(result);+ };++ const summarizeOutput = () => stderr.trim() || stdout.trim() || 'No Output';++ const timer = setTimeout(() => {+ child.kill('SIGKILL');+ finish({+ content: '',+ error: `Isolated tool worker timed out for ${apiName} after ${workerTimeout}ms`,+ success: false,+ });+ }, workerTimeout);++ child.stdout.setEncoding('utf8');+ child.stderr.setEncoding('utf8');+ child.stdout.on('data', (chunk) => {+ stdout += chunk;+ });+ child.stderr.on('data', (chunk) => {+ stderr += chunk;+ });+ child.on('error', (error) => {+ finish({+ content: '',+ error: `Isolated tool worker failed for ${apiName}: ${error.message}`,+ success: false,+ });+ });+ child.on('close', (code, signal) => {+ if (code === 0 && !signal) {+ const output = stdout.trim();+ if (!output) {+ finish({+ content: '',+ error: `Isolated tool worker produced no output for ${apiName}`,+ success: false,+ });+ return;+ }++ try {+ finish(JSON.parse(output));+ return;+ } catch (error) {+ const errorMsg = error instanceof Error ? error.message : String(error);+ const workerOutput = summarizeOutput();+ finish({+ content: '',+ error: `Isolated tool worker returned invalid JSON for ${apiName}: ${errorMsg}. Output: ${workerOutput}`,+ success: false,+ });+ return;+ }+ }++ const exitReason = signal+ ? `signal ${signal}`+ : typeof code === 'number'+ ? `exit code ${code}`+ : 'unknown exit';+ const workerOutput = summarizeOutput();+ finish({+ content: '',+ error: `Isolated tool worker failed for ${apiName} with ${exitReason}: ${workerOutput}`,+ success: false,+ });+ });+ });+}