🤯 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
🔨 chore(agent-runtime): dispatch client-executor tools via Agent Gateway WS (#13769)
Arvin Xu3c2fc7f368a8
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 03b90bfe7e6..6d7a4d89366 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -46,6 +46,7 @@ import {type ToolExecutionService,} from '@/server/services/toolExecution';+import { dispatchClientTool } from './dispatchClientTool';import { classifyLLMError, type LLMErrorKind } from './llmErrorClassification';import { type IStreamEventManager } from './types';@@ -1346,28 +1347,45 @@ export const createRuntimeExecutors = (),};- // Execute tool using ToolExecutionService- log(`[${operationLogId}] Executing tool ${toolName} ...`);- const execution = await executeToolWithRetry(- () =>- toolExecutionService.executeTool(chatToolPayload, {- activeDeviceId: state.metadata?.activeDeviceId,- agentId: state.metadata?.agentId,- memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,- serverDB: ctx.serverDB,- taskId: state.metadata?.taskId,- toolManifestMap: effectiveManifestMap,- toolResultMaxLength,- topicId: ctx.topicId,- userId: ctx.userId,- }),- {- isInterrupted: () => isOperationInterrupted(ctx),- maxRetries: TOOL_MAX_RETRIES,- operationLogId,- toolName,- },- );+ // Route to client via Agent Gateway WS when the tool is marked+ // executor='client' and the current stream manager can reach a gateway.+ // Falls through to the normal server path if either is unavailable.+ const canDispatchToClient =+ chatToolPayload.executor === 'client' &&+ typeof streamManager.sendToolExecute === 'function';++ let execution: { result: ToolExecutionResultResponse; attempts: number };+ if (canDispatchToClient) {+ log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);+ const dispatchResult = await dispatchClientTool(chatToolPayload, {+ operationId,+ streamManager,+ });+ execution = { attempts: 1, result: dispatchResult };+ } else {+ // Execute tool using ToolExecutionService+ log(`[${operationLogId}] Executing tool ${toolName} ...`);+ execution = await executeToolWithRetry(+ () =>+ toolExecutionService.executeTool(chatToolPayload, {+ activeDeviceId: state.metadata?.activeDeviceId,+ agentId: state.metadata?.agentId,+ memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,+ serverDB: ctx.serverDB,+ taskId: state.metadata?.taskId,+ toolManifestMap: effectiveManifestMap,+ toolResultMaxLength,+ topicId: ctx.topicId,+ userId: ctx.userId,+ }),+ {+ isInterrupted: () => isOperationInterrupted(ctx),+ maxRetries: TOOL_MAX_RETRIES,+ operationLogId,+ toolName,+ },+ );+ }const executionResult = execution.result;const executionTime = executionResult.executionTime;@@ -1626,26 +1644,40 @@ export const createRuntimeExecutors = (const batchAgentConfig = state.metadata?.agentConfig;- const execution = await executeToolWithRetry(- () =>- toolExecutionService.executeTool(chatToolPayload, {- activeDeviceId: state.metadata?.activeDeviceId,- agentId: state.metadata?.agentId,- memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,- serverDB: ctx.serverDB,- taskId: state.metadata?.taskId,- toolManifestMap: batchManifestMap,- toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,- topicId: ctx.topicId,- userId: ctx.userId,- }),- {- isInterrupted: () => isOperationInterrupted(ctx),- maxRetries: TOOL_MAX_RETRIES,- operationLogId,- toolName,- },- );+ const canDispatchToClient =+ chatToolPayload.executor === 'client' &&+ typeof streamManager.sendToolExecute === 'function';++ let execution: { result: ToolExecutionResultResponse; attempts: number };+ if (canDispatchToClient) {+ log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);+ const dispatchResult = await dispatchClientTool(chatToolPayload, {+ operationId,+ streamManager,+ });+ execution = { attempts: 1, result: dispatchResult };+ } else {+ execution = await executeToolWithRetry(+ () =>+ toolExecutionService.executeTool(chatToolPayload, {+ activeDeviceId: state.metadata?.activeDeviceId,+ agentId: state.metadata?.agentId,+ memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,+ serverDB: ctx.serverDB,+ taskId: state.metadata?.taskId,+ toolManifestMap: batchManifestMap,+ toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,+ topicId: ctx.topicId,+ userId: ctx.userId,+ }),+ {+ isInterrupted: () => isOperationInterrupted(ctx),+ maxRetries: TOOL_MAX_RETRIES,+ operationLogId,+ toolName,+ },+ );+ }const executionResult = execution.result;const executionTime = executionResult.executionTime;diff --git a/src/server/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts b/src/server/modules/AgentRuntime/__tests__/dispatchClientTool.test.tsnew file mode 100644index 00000000000..6380d1a42ac--- /dev/null+++ b/src/server/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts@@ -0,0 +1,161 @@+import type { ChatToolPayload } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { dispatchClientTool } from '../dispatchClientTool';+import type { IStreamEventManager } from '../types';++// Mock Redis before importing the SUT so the module-level getter sees it.+const mockBlpop = vi.fn();+const mockDisconnect = vi.fn();+const mockDuplicate = vi.fn();+let currentRedis: any;++vi.mock('../redis', () => ({+ getAgentRuntimeRedisClient: () => currentRedis,+}));++function makePayload(overrides: Partial<ChatToolPayload> = {}): ChatToolPayload {+ return {+ apiName: 'readFile',+ arguments: '{"path":"/tmp/x"}',+ executor: 'client',+ id: 'call-1',+ identifier: 'local-system',+ type: 'default' as any,+ ...overrides,+ };+}++function makeStreamManager(+ sendToolExecute?: IStreamEventManager['sendToolExecute'],+): IStreamEventManager {+ return {+ cleanupOperation: vi.fn(),+ disconnect: vi.fn(),+ getActiveOperationsCount: vi.fn(),+ getStreamHistory: vi.fn(),+ publishAgentRuntimeEnd: vi.fn(),+ publishAgentRuntimeInit: vi.fn(),+ publishStreamChunk: vi.fn(),+ publishStreamEvent: vi.fn(),+ sendToolExecute,+ subscribeStreamEvents: vi.fn(),+ } as unknown as IStreamEventManager;+}++describe('dispatchClientTool', () => {+ beforeEach(() => {+ mockBlpop.mockReset();+ mockDisconnect.mockReset();+ mockDuplicate.mockReset();++ const blockingClient = {+ blpop: mockBlpop,+ disconnect: mockDisconnect,+ };+ mockDuplicate.mockReturnValue(blockingClient);++ currentRedis = {+ duplicate: mockDuplicate,+ pipeline: vi.fn(() => ({+ exec: vi.fn().mockResolvedValue([]),+ expire: vi.fn().mockReturnThis(),+ lpush: vi.fn().mockReturnThis(),+ })),+ };+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it('returns gateway_unsupported when streamManager.sendToolExecute is missing', async () => {+ const streamManager = makeStreamManager(undefined);++ const result = await dispatchClientTool(makePayload(), {+ operationId: 'op-1',+ streamManager,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('gateway_unsupported');+ expect(mockDuplicate).not.toHaveBeenCalled();+ });++ it('returns redis_unavailable when Redis is not configured', async () => {+ currentRedis = null;+ const streamManager = makeStreamManager(vi.fn());++ const result = await dispatchClientTool(makePayload(), {+ operationId: 'op-1',+ streamManager,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('redis_unavailable');+ });++ it('sends tool_execute, BLPOPs, and returns the parsed result on success', async () => {+ const sendToolExecute = vi.fn().mockResolvedValue(undefined);+ const streamManager = makeStreamManager(sendToolExecute);++ mockBlpop.mockResolvedValue([+ 'tool_result:call-1',+ JSON.stringify({+ content: 'file contents',+ success: true,+ toolCallId: 'call-1',+ }),+ ]);++ const result = await dispatchClientTool(makePayload(), {+ operationId: 'op-1',+ streamManager,+ });++ expect(sendToolExecute).toHaveBeenCalledTimes(1);+ const sendCall = sendToolExecute.mock.calls[0];+ expect(sendCall[0]).toBe('op-1');+ expect(sendCall[1]).toMatchObject({+ apiName: 'readFile',+ identifier: 'local-system',+ toolCallId: 'call-1',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('file contents');+ expect(result.error).toBeUndefined();+ expect(mockDisconnect).toHaveBeenCalled();+ });++ it('returns a timeout result and still disconnects when BLPOP times out', async () => {+ const sendToolExecute = vi.fn().mockResolvedValue(undefined);+ const streamManager = makeStreamManager(sendToolExecute);++ mockBlpop.mockResolvedValue(null);++ const result = await dispatchClientTool(makePayload(), {+ operationId: 'op-1',+ streamManager,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('timeout');+ expect(mockDisconnect).toHaveBeenCalled();+ });++ it('returns a dispatch_failed result when sendToolExecute rejects', async () => {+ const sendToolExecute = vi.fn().mockRejectedValue(new Error('gateway down'));+ const streamManager = makeStreamManager(sendToolExecute);++ const result = await dispatchClientTool(makePayload(), {+ operationId: 'op-1',+ streamManager,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('dispatch_failed');+ expect(result.error?.message).toBe('gateway down');+ expect(mockDisconnect).toHaveBeenCalled();+ });+});diff --git a/src/server/modules/AgentRuntime/dispatchClientTool.ts b/src/server/modules/AgentRuntime/dispatchClientTool.tsnew file mode 100644index 00000000000..abb30be1837--- /dev/null+++ b/src/server/modules/AgentRuntime/dispatchClientTool.ts@@ -0,0 +1,144 @@+import type { ChatToolPayload } from '@lobechat/types';+import debug from 'debug';++import type { ToolExecutionResultResponse } from '@/server/services/toolExecution/types';++import { getAgentRuntimeRedisClient } from './redis';+import type { ToolResultPayload } from './ToolResultWaiter';+import { ToolResultWaiter } from './ToolResultWaiter';+import type { IStreamEventManager } from './types';++const log = debug('lobe-server:agent-runtime:dispatch-client-tool');++/**+ * Default per-tool execution budget when the payload doesn't carry one.+ */+const DEFAULT_EXECUTION_TIMEOUT_MS = 60_000;++/**+ * Hard cap tied to a single Vercel serverless function window. Phase 6.3c+ * relaxes this by persisting pending-tool state and resuming on a fresh+ * invocation.+ */+const MAX_EXECUTION_TIMEOUT_MS = 270_000;++interface DispatchContext {+ operationId: string;+ streamManager: IStreamEventManager;+}++const clampTimeout = (value: number): number =>+ Math.min(Math.max(value, 1_000), MAX_EXECUTION_TIMEOUT_MS);++const buildTimeoutResult = (executionTime: number): ToolExecutionResultResponse => ({+ content: '',+ error: { message: 'Tool execution timed out', type: 'timeout' },+ executionTime,+ success: false,+});++const buildErrorResult = (+ executionTime: number,+ error: unknown,+ type = 'dispatch_failed',+): ToolExecutionResultResponse => ({+ content: '',+ error: {+ message: error instanceof Error ? error.message : String(error),+ type,+ },+ executionTime,+ success: false,+});++/**+ * Dispatch a tool execution to the client via Agent Gateway WebSocket and+ * block-await the result on Redis. Never throws: any error path produces a+ * failed ClientToolExecutionResult so the agent loop can continue.+ *+ * The caller is expected to gate on `typeof streamManager.sendToolExecute ===+ * 'function'` and `chatToolPayload.executor === 'client'` before invoking.+ */+export async function dispatchClientTool(+ chatToolPayload: ChatToolPayload,+ ctx: DispatchContext,+): Promise<ToolExecutionResultResponse> {+ const { operationId, streamManager } = ctx;+ const startedAt = Date.now();++ if (typeof streamManager.sendToolExecute !== 'function') {+ return buildErrorResult(+ 0,+ 'Gateway notifier does not support tool_execute',+ 'gateway_unsupported',+ );+ }++ const redis = getAgentRuntimeRedisClient();+ if (!redis) {+ return buildErrorResult(+ 0,+ 'Redis is not available for tool result waiting',+ 'redis_unavailable',+ );+ }++ // BLPOP holds the underlying socket, so we need a dedicated connection per+ // dispatch. Cleanup in `finally` so we never leak on the error path.+ const blockingClient = redis.duplicate();+ const waiter = new ToolResultWaiter(blockingClient, redis);++ const timeoutMs = clampTimeout(DEFAULT_EXECUTION_TIMEOUT_MS);++ try {+ log(+ '[%s] dispatching client tool %s/%s (toolCallId=%s, timeout=%dms)',+ operationId,+ chatToolPayload.identifier,+ chatToolPayload.apiName,+ chatToolPayload.id,+ timeoutMs,+ );++ await streamManager.sendToolExecute(operationId, {+ apiName: chatToolPayload.apiName,+ arguments: chatToolPayload.arguments,+ executionTimeoutMs: timeoutMs,+ identifier: chatToolPayload.identifier,+ toolCallId: chatToolPayload.id,+ });++ const result = await waiter.waitForResult(chatToolPayload.id, timeoutMs);+ const executionTime = Date.now() - startedAt;++ if (!result) {+ log(+ '[%s] client tool %s timed out after %dms',+ operationId,+ chatToolPayload.id,+ executionTime,+ );+ return buildTimeoutResult(executionTime);+ }++ return projectToExecutionResult(result, executionTime);+ } catch (error) {+ const executionTime = Date.now() - startedAt;+ log('[%s] client tool dispatch failed: %O', operationId, error);+ return buildErrorResult(executionTime, error);+ } finally {+ blockingClient.disconnect();+ }+}++function projectToExecutionResult(+ payload: ToolResultPayload,+ executionTime: number,+): ToolExecutionResultResponse {+ return {+ content: payload.content ?? '',+ error: payload.error,+ executionTime,+ success: payload.success,+ };+}diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex d774a5f3cd6..d48a9722033 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -616,6 +616,20 @@ export class AiAgentService {toolSourceMap[manifest.identifier] = 'klavis';}+ // Mark tools that must run on the client (desktop Electron) because they+ // require local IPC / subprocess capabilities:+ // - local-system builtin: Electron IPC for file + command execution+ // - stdio MCP plugins: subprocess lives on the user's machine+ // Dispatcher in RuntimeExecutors reads this to route via Agent Gateway WS.+ if (manifestMap.has(LocalSystemManifest.identifier)) {+ toolExecutorMap[LocalSystemManifest.identifier] = 'client';+ }+ for (const plugin of installedPlugins) {+ if (plugin.customParams?.mcp?.type === 'stdio' && manifestMap.has(plugin.identifier)) {+ toolExecutorMap[plugin.identifier] = 'client';+ }+ }+log('execAgent: generated %d tools, %d lobehub skills, %d klavis tools',tools?.length ?? 0,