π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: wire server-side exec_task/exec_tasks for callAgent async mode (#14913)
LiJiand359a83ade1d
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 23839649ef9..b27ef7e1dfa 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -2,6 +2,9 @@ import {type AgentEvent,type AgentInstruction,type AgentInstructionCompressContext,+ type AgentInstructionExecSubAgent,+ type AgentInstructionExecSubAgents,+ type AgentRuntimeContext,type AgentState,type CallLLMPayload,type GeneralAgentCallLLMResultPayload,@@ -30,7 +33,12 @@ import {import { parse } from '@lobechat/conversation-flow';import { consumeStreamUntilDone } from '@lobechat/model-runtime';import { chainCompressContext } from '@lobechat/prompts';-import { type ChatToolPayload, type MessageToolCall, type UIChatMessage } from '@lobechat/types';+import {+ type ChatToolPayload,+ type ExecSubAgentTaskParams,+ type MessageToolCall,+ type UIChatMessage,+} from '@lobechat/types';import { sanitizeToolCallArguments, serializePartsForStorage } from '@lobechat/utils';import debug from 'debug';@@ -210,6 +218,12 @@ export interface RuntimeExecutorContext {botPlatformContext?: BotPlatformContext;discordContext?: any;evalContext?: EvalContext;+ /**+ * Callback to spawn a sub-agent task server-side.+ * Injected by AiAgentService so exec_sub_agent / exec_sub_agents executors+ * can dispatch callAgent-triggered tasks without a circular import.+ */+ execSubAgentTask?: (params: ExecSubAgentTaskParams) => Promise<unknown>;hookDispatcher?: HookDispatcher;loadAgentState?: (operationId: string) => Promise<AgentState | null>;messageModel: MessageModel;@@ -1853,6 +1867,15 @@ export const createRuntimeExecutors = (log('[%s:%d] Tool execution completed', operationId, stepIndex);+ // When the tool result carries an execSubAgent / execSubAgents state the+ // GeneralChatAgent needs `stop: true` in the payload to detect it and+ // emit the matching exec_sub_agent / exec_sub_agents instruction. Without+ // this flag the agent falls through to the normal LLM-call path and the+ // sub-agent is never spawned.+ const execTaskStateType = executionResult.state?.type as string | undefined;+ const isExecTaskState =+ execTaskStateType === 'execSubAgent' || execTaskStateType === 'execSubAgents';+return {events,newState,@@ -1863,6 +1886,7 @@ export const createRuntimeExecutors = (isSuccess,// Pass tool message ID as parentMessageId for the next LLM callparentMessageId: toolMessageId,+ ...(isExecTaskState && { stop: true }),toolCall: chatToolPayload,toolCallId: chatToolPayload.id,},@@ -2426,6 +2450,210 @@ export const createRuntimeExecutors = (};},+ /**+ * Server-side exec_sub_agent executor+ *+ * Mirrors the client-side exec_sub_agent executor in createAgentExecutors.ts+ * but runs entirely server-side (no polling required). Flow:+ * 1. Create a task message (role: 'task') as a placeholder visible in the UI.+ * 2. Fire execSubAgentTask via the injected callback so the sub-agent runs as+ * an independent QStash operation.+ * 3. Return a sub_agent_result context so GeneralChatAgent calls the LLM once+ * more and the parent agent can acknowledge the delegation.+ */+ exec_sub_agent: async (instruction, state) => {+ const { payload } = instruction as AgentInstructionExecSubAgent;+ const { parentMessageId, task } = payload;+ const events: AgentEvent[] = [];+ const { operationId } = ctx;+ const taskLogId = `${operationId}:exec_sub_agent`;++ const topicId = ctx.topicId ?? state.metadata?.topicId;+ const agentId = state.metadata?.agentId;+ // targetAgentId is a cloud extension injected by agentManagement.callAgent+ const targetAgentId = (task as any).targetAgentId ?? agentId;++ let taskMessageId: string | undefined;+ try {+ const taskMessage = await ctx.messageModel.create({+ agentId: agentId!,+ content: '',+ metadata: {+ instruction: task.instruction,+ taskTitle: task.description,+ ...(targetAgentId && targetAgentId !== agentId && { targetAgentId }),+ },+ parentId: parentMessageId,+ role: 'task',+ threadId: state.metadata?.threadId ?? undefined,+ topicId: topicId!,+ });+ taskMessageId = taskMessage.id;+ log('[%s] Created task message: %s', taskLogId, taskMessageId);+ } catch (error) {+ log('[%s] Failed to create task message: %O', taskLogId, error);+ }++ const effectiveTaskMessageId = taskMessageId ?? parentMessageId;++ let dispatched = false;+ if (ctx.execSubAgentTask && topicId && agentId) {+ try {+ await ctx.execSubAgentTask({+ agentId: targetAgentId,+ groupId: state.metadata?.groupId ?? undefined,+ instruction: task.instruction,+ parentMessageId: effectiveTaskMessageId,+ parentOperationId: operationId,+ timeout: task.timeout,+ title: task.description,+ topicId,+ });+ dispatched = true;+ log('[%s] Spawned sub-agent task for agent %s', taskLogId, targetAgentId);+ } catch (error) {+ log('[%s] Failed to spawn sub-agent task: %O', taskLogId, error);+ if (taskMessageId) {+ try {+ await ctx.messageModel.update(taskMessageId, {+ content: `Task failed to start: ${(error as Error).message}`,+ });+ } catch {+ // best-effort+ }+ }+ }+ } else {+ log('[%s] execSubAgentTask not available, skipping sub-agent dispatch', taskLogId);+ }++ return {+ events,+ newState: state,+ nextContext: {+ payload: {+ parentMessageId: effectiveTaskMessageId,+ result: {+ success: dispatched,+ taskMessageId: effectiveTaskMessageId,+ threadId: '',+ },+ },+ phase: 'sub_agent_result',+ session: {+ messageCount: state.messages.length,+ sessionId: operationId,+ status: 'running',+ stepCount: state.stepCount + 1,+ },+ } as unknown as AgentRuntimeContext,+ };+ },++ /**+ * Server-side exec_sub_agents executor+ *+ * Same as exec_sub_agent but for a batch. Each sub-agent is fired+ * independently via execSubAgentTask and a task message is created for each.+ */+ exec_sub_agents: async (instruction, state) => {+ const { payload } = instruction as AgentInstructionExecSubAgents;+ const { parentMessageId, tasks } = payload;+ const events: AgentEvent[] = [];+ const { operationId } = ctx;+ const taskLogId = `${operationId}:exec_sub_agents`;++ const topicId = ctx.topicId ?? state.metadata?.topicId;+ const agentId = state.metadata?.agentId;++ log('[%s] Starting batch of %d tasks', taskLogId, tasks.length);++ let lastTaskMessageId: string | undefined;+ const taskResults: Array<{ success: boolean; taskMessageId: string; threadId: string }> = [];++ for (const task of tasks) {+ const targetAgentId = (task as any).targetAgentId ?? agentId;+ let taskMessageId: string | undefined;++ try {+ const taskMessage = await ctx.messageModel.create({+ agentId: agentId!,+ content: '',+ metadata: {+ instruction: task.instruction,+ taskTitle: task.description,+ ...(targetAgentId && targetAgentId !== agentId && { targetAgentId }),+ },+ parentId: parentMessageId,+ role: 'task',+ threadId: state.metadata?.threadId ?? undefined,+ topicId: topicId!,+ });+ taskMessageId = taskMessage.id;+ lastTaskMessageId = taskMessageId;+ } catch (error) {+ log('[%s] Failed to create task message for "%s": %O', taskLogId, task.description, error);+ }++ let taskDispatched = false;+ if (ctx.execSubAgentTask && topicId && agentId) {+ try {+ await ctx.execSubAgentTask({+ agentId: targetAgentId,+ groupId: state.metadata?.groupId ?? undefined,+ instruction: task.instruction,+ parentMessageId: taskMessageId ?? parentMessageId,+ parentOperationId: operationId,+ timeout: task.timeout,+ title: task.description,+ topicId,+ });+ taskDispatched = true;+ log(+ '[%s] Spawned sub-agent task "%s" for agent %s',+ taskLogId,+ task.description,+ targetAgentId,+ );+ } catch (error) {+ log('[%s] Failed to spawn task "%s": %O', taskLogId, task.description, error);+ if (taskMessageId) {+ try {+ await ctx.messageModel.update(taskMessageId, {+ content: `Task failed to start: ${(error as Error).message}`,+ });+ } catch {+ // best-effort+ }+ }+ }+ }+ taskResults.push({+ success: taskDispatched,+ taskMessageId: taskMessageId ?? parentMessageId,+ threadId: '',+ });+ }++ return {+ events,+ newState: state,+ nextContext: {+ payload: {+ parentMessageId: lastTaskMessageId ?? parentMessageId,+ results: taskResults,+ },+ phase: 'sub_agents_batch_result',+ session: {+ messageCount: state.messages.length,+ sessionId: operationId,+ status: 'running',+ stepCount: state.stepCount + 1,+ },+ } as unknown as AgentRuntimeContext,+ };+ },+/*** Complete runtime execution*/diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 96ad15ba315..53aafb739ac 100644--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -3826,4 +3826,147 @@ describe('RuntimeExecutors', () => {});});});++ // βββ callAgent server-side exec_sub_agent fix ββββββββββββββββββββββββββββββ+ describe('call_tool β exec_sub_agent (callAgent async mode)', () => {+ const createMockState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: createMockCost(),+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ maxSteps: 100,+ messages: [],+ metadata: {+ agentId: 'parent-agent-id',+ topicId: 'topic-123',+ },+ modelRuntimeConfig: { model: 'gpt-4', provider: 'openai' },+ operationId: 'op-123',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: createMockUsage(),+ ...overrides,+ });++ it('call_tool sets stop:true in tool_result payload when tool returns execSubAgent state', async () => {+ // Simulate agentManagement.callAgent returning execSubAgent state+ mockToolExecutionService.executeTool.mockResolvedValue({+ content: 'π Triggered async task to call agent "target-agent"',+ executionTime: 10,+ state: {+ parentMessageId: 'tool-msg-id',+ task: {+ description: 'Call agent target-agent',+ instruction: 'Do something',+ targetAgentId: 'target-agent-id',+ timeout: 1_800_000,+ },+ type: 'execSubAgent',+ },+ success: true,+ });++ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();+ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-id',+ toolCalling: {+ apiName: 'callAgent',+ arguments: JSON.stringify({+ agentId: 'target-agent-id',+ instruction: 'Do something',+ runAsTask: true,+ }),+ id: 'tool-call-1',+ identifier: 'lobe-agent-management',+ type: 'default' as const,+ },+ },+ type: 'call_tool' as const,+ };++ const result = await executors.call_tool!(instruction, state);++ expect(result.nextContext?.phase).toBe('tool_result');+ expect((result.nextContext?.payload as any).stop).toBe(true);+ });++ it('exec_sub_agent executor creates task message and calls execSubAgentTask callback', async () => {+ const mockExecSubAgentTask = vi+ .fn()+ .mockResolvedValue({ success: true, operationId: 'child-op', threadId: 'thread-child' });+ const ctxWithCallback = {+ ...ctx,+ execSubAgentTask: mockExecSubAgentTask,+ topicId: 'topic-123',+ };++ const executors = createRuntimeExecutors(ctxWithCallback);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'tool-msg-id',+ task: {+ description: 'Call agent target-agent',+ instruction: 'Do something useful',+ targetAgentId: 'target-agent-id',+ timeout: 1_800_000,+ },+ },+ type: 'exec_sub_agent' as const,+ };++ const result = await executors.exec_sub_agent!(instruction as any, state);++ // Task message created with role:'task'+ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'parent-agent-id',+ role: 'task',+ parentId: 'tool-msg-id',+ topicId: 'topic-123',+ }),+ );++ // execSubAgentTask callback fired with targetAgentId+ expect(mockExecSubAgentTask).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'target-agent-id',+ instruction: 'Do something useful',+ topicId: 'topic-123',+ parentOperationId: 'op-123',+ }),+ );++ // Returns sub_agent_result so GeneralChatAgent continues with LLM call+ expect(result.nextContext?.phase).toBe('sub_agent_result');+ });++ it('exec_sub_agent gracefully skips dispatch when execSubAgentTask not injected', async () => {+ // No callback injected (e.g. in tests that don't set it up)+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'tool-msg-id',+ task: {+ description: 'Call agent target-agent',+ instruction: 'Do something',+ targetAgentId: 'target-agent-id',+ },+ },+ type: 'exec_sub_agent' as const,+ };++ const result = await executors.exec_sub_agent!(instruction as any, state);++ // Should still return sub_agent_result (not crash)+ expect(result.nextContext?.phase).toBe('sub_agent_result');+ // Task message still created for UI+ expect(mockMessageModel.create).toHaveBeenCalled();+ });+ });});diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex 888741d2c75..7b906fd8121 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -8,7 +8,12 @@ import { AgentRuntime, findInMessages, GeneralChatAgent } from '@lobechat/agent-import type { ISnapshotStore } from '@lobechat/agent-tracing';import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';import { getModelPropertyWithFallback } from '@lobechat/model-runtime';-import { AgentRuntimeErrorType, ChatErrorType, type ChatMessageError } from '@lobechat/types';+import {+ AgentRuntimeErrorType,+ ChatErrorType,+ type ChatMessageError,+ type ExecSubAgentTaskParams,+} from '@lobechat/types';import debug from 'debug';import urlJoin from 'url-join';@@ -17,8 +22,10 @@ import { type LobeChatDatabase } from '@/database/type';import { appEnv } from '@/envs/app';import { type AgentRuntimeCoordinatorOptions } from '@/server/modules/AgentRuntime';import { AgentRuntimeCoordinator, createStreamEventManager } from '@/server/modules/AgentRuntime';-import { type RuntimeExecutorContext } from '@/server/modules/AgentRuntime/RuntimeExecutors';-import { createRuntimeExecutors } from '@/server/modules/AgentRuntime/RuntimeExecutors';+import {+ createRuntimeExecutors,+ type RuntimeExecutorContext,+} from '@/server/modules/AgentRuntime/RuntimeExecutors';import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';@@ -116,6 +123,12 @@ export interface AgentRuntimeServiceOptions {* Allows injection of custom stateManager and streamEventManager*/coordinatorOptions?: AgentRuntimeCoordinatorOptions;+ /**+ * Callback to spawn a sub-agent task from within a running server-side agent.+ * Injected by AiAgentService to wire up the exec_task / exec_tasks executors+ * without creating a circular import between RuntimeExecutors and AiAgentService.+ */+ execSubAgentTask?: (params: ExecSubAgentTaskParams) => Promise<unknown>;/*** Custom QueueService* Set to null to disable queue scheduling (for synchronous execution tests)@@ -155,6 +168,7 @@ export class AgentRuntimeService {private agentFactory?: (config: GeneralAgentConfig) => Agent;private completionLifecycle: CompletionLifecycle;private coordinator: AgentRuntimeCoordinator;+ private execSubAgentTaskCallback?: (params: ExecSubAgentTaskParams) => Promise<unknown>;private humanIntervention: HumanInterventionHandler;private streamManager: IStreamEventManager;private queueService: QueueService | null;@@ -185,6 +199,7 @@ export class AgentRuntimeService {options?.snapshotStore ?? this.createDefaultSnapshotStore(),);this.agentFactory = options?.agentFactory;+ this.execSubAgentTaskCallback = options?.execSubAgentTask;this.serverDB = db;this.userId = userId;this.messageModel = new MessageModel(db, this.userId);@@ -1360,6 +1375,7 @@ export class AgentRuntimeService {discordContext: metadata?.discordContext,userTimezone: metadata?.userTimezone,evalContext: metadata?.evalContext,+ execSubAgentTask: this.execSubAgentTaskCallback,hookDispatcher,loadAgentState: this.coordinator.loadAgentState.bind(this.coordinator),messageModel: this.messageModel,diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 5464761e45b..1131d0fb359 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -263,7 +263,10 @@ export class AiAgentService {this.taskModel = new TaskModel(db, userId);this.threadModel = new ThreadModel(db, userId);this.topicModel = new TopicModel(db, userId);- this.agentRuntimeService = new AgentRuntimeService(db, userId, options?.runtimeOptions);+ this.agentRuntimeService = new AgentRuntimeService(db, userId, {+ ...options?.runtimeOptions,+ execSubAgentTask: this.execSubAgentTask.bind(this),+ });this.marketService = new MarketService({ userInfo: { userId } });this.klavisService = new KlavisService({ db, userId });}