🤯 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: move sub-agent executors into agent-runtime (#16925)
Arvin Xu798f3167dff1
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.tsindex 85b6ee20fb9..0f3f085bce6 100644--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts@@ -2,6 +2,8 @@ import type { AgentInstruction, InstructionExecutor } from '@lobechat/agent-runtimport {callTool as createCallToolExecutor,callToolsBatch as createCallToolsBatchExecutor,+ execSubAgent as createExecSubAgentExecutor,+ execSubAgents as createExecSubAgentsExecutor,finish as createFinishExecutor,requestHumanApprove as createRequestHumanApproveExecutor,resolveAbortedTools as createResolveAbortedToolsExecutor,@@ -12,7 +14,6 @@ import { buildHost } from './buildHost';import type { RuntimeExecutorContext } from './context';import { callLlm } from './executors/callLlm';import { compressContext } from './executors/compressContext';-import { execSubAgent, execSubAgents } from './executors/execSubAgent';export { type RuntimeExecutorContext } from './context';@@ -28,8 +29,8 @@ export const createRuntimeExecutors = (call_tool: createCallToolExecutor(host),call_tools_batch: createCallToolsBatchExecutor(host),compress_context: compressContext(ctx),- exec_sub_agent: execSubAgent(ctx),- exec_sub_agents: execSubAgents(ctx),+ exec_sub_agent: createExecSubAgentExecutor(host),+ exec_sub_agents: createExecSubAgentsExecutor(host),// Migrated into @lobechat/agent-runtime as part of the IO transport port// abstraction — the server now only registers adapters via buildHost.finish: createFinishExecutor(host),diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 2dd1d344d47..8e24de0a331 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -5319,7 +5319,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {expect(result.nextContext).toBeUndefined();});- it('exec_sub_agent executor creates task message and calls execSubAgent callback', async () => {+ it('exec_sub_agent executor dispatches from the source parent message', async () => {const mockExecSubAgent = vi.fn().mockResolvedValue({ success: true, operationId: 'child-op', threadId: 'thread-child' });@@ -5347,26 +5347,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {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',- metadata: expect.objectContaining({- targetAgentId: 'target-agent-id',- }),- role: 'task',- parentId: 'tool-msg-id',- topicId: 'topic-123',- }),- );+ expect(mockMessageModel.create).not.toHaveBeenCalled();// execSubAgent callback fired with targetAgentIdexpect(mockExecSubAgent).toHaveBeenCalledWith(expect.objectContaining({agentId: 'target-agent-id',instruction: 'Do something useful',- topicId: 'topic-123',parentOperationId: 'op-123',+ parentMessageId: 'tool-msg-id',+ topicId: 'topic-123',}),);@@ -5433,10 +5423,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {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();+ expect(mockMessageModel.create).not.toHaveBeenCalled();});});});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.tsnew file mode 100644index 00000000000..6bc30e2a0db--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts@@ -0,0 +1,59 @@+import type { SubAgentTransport } from '@lobechat/agent-runtime';+import type {+ ExecSubAgentParams,+ ExecSubAgentResult,+ ExecVirtualSubAgentParams,+} from '@lobechat/types';+import { pickString, toRecord } from '@lobechat/utils/object';++import type { RuntimeExecutorContext } from '../context';++const fallbackResult = (error: string): ExecSubAgentResult => ({+ assistantMessageId: '',+ error,+ operationId: '',+ success: false,+ threadId: '',+});++const normalizeResult = (value: unknown): ExecSubAgentResult => {+ const result = toRecord(value);+ if (!result) {+ return {+ assistantMessageId: '',+ operationId: '',+ success: true,+ threadId: '',+ };+ }++ return {+ assistantMessageId: pickString(result.assistantMessageId) ?? '',+ error: pickString(result.error),+ operationId: pickString(result.operationId) ?? '',+ success: result.success !== false,+ threadId: pickString(result.threadId) ?? '',+ };+};++/**+ * Server {@link SubAgentTransport} adapter — delegates child-run creation to+ * callbacks injected by AiAgentService while the package owns executor flow.+ */+export class ServerSubAgentTransport implements SubAgentTransport {+ constructor(private readonly ctx: RuntimeExecutorContext) {}++ async execSubAgent(params: ExecSubAgentParams): Promise<ExecSubAgentResult> {+ if (!this.ctx.execSubAgent) return fallbackResult('Sub-agent dispatch is not available.');++ return normalizeResult(await this.ctx.execSubAgent(params));+ }++ async execVirtualSubAgent(params: ExecVirtualSubAgentParams): Promise<ExecSubAgentResult> {+ if (!this.ctx.execVirtualSubAgent) {+ return fallbackResult('Virtual sub-agent dispatch is not available.');+ }++ return normalizeResult(await this.ctx.execVirtualSubAgent(params));+ }+}diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.tsindex b0342d2daeb..70d21b282e9 100644--- a/apps/server/src/modules/AgentRuntime/buildHost.ts+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts@@ -4,6 +4,7 @@ import { ServerLifecycleSink } from './adapters/ServerLifecycleSink';import { ServerMessageTransport } from './adapters/ServerMessageTransport';import { ServerOperationStore } from './adapters/ServerOperationStore';import { ServerStreamSink } from './adapters/ServerStreamSink';+import { ServerSubAgentTransport } from './adapters/ServerSubAgentTransport';import { ServerToolTransport } from './adapters/ServerToolTransport';import type { RuntimeExecutorContext } from './context';import { buildPostProcessUrl } from './executorHelpers';@@ -43,6 +44,7 @@ export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => ({ctx.topicId,),stream: new ServerStreamSink(ctx.streamManager, ctx.operationId),+ subAgent: ctx.execSubAgent ? new ServerSubAgentTransport(ctx) : undefined,tools: new ServerToolTransport(ctx),},});diff --git a/apps/server/src/modules/AgentRuntime/executors/execSubAgent.ts b/apps/server/src/modules/AgentRuntime/executors/execSubAgent.tsdeleted file mode 100644index 72d9e6eda2f..00000000000--- a/apps/server/src/modules/AgentRuntime/executors/execSubAgent.ts+++ /dev/null@@ -1,256 +0,0 @@-import {- type AgentEvent,- type AgentInstructionExecSubAgent,- type AgentInstructionExecSubAgents,- type AgentRuntimeContext,- type InstructionExecutor,-} from '@lobechat/agent-runtime';--import { type RuntimeExecutorContext } from '../context';-import { log } from '../executorHelpers';--export const execSubAgent =- (ctx: RuntimeExecutorContext): InstructionExecutor =>- 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;-- if (state.metadata?.isSubAgent === true) {- log('[%s] Nested sub-agent dispatch blocked', taskLogId);- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- result: {- error: 'Sub-agent calls cannot be triggered from within another sub-agent.',- success: false,- taskMessageId: parentMessageId,- threadId: '',- },- },- phase: 'sub_agent_result',- session: {- messageCount: state.messages.length,- sessionId: operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as unknown as AgentRuntimeContext,- };- }-- let taskMessageId: string | undefined;- try {- const taskMessage = await ctx.messageModel.create({- agentId: agentId!,- content: '',- groupId: state.metadata?.groupId ?? undefined,- 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.execSubAgent && topicId && agentId) {- try {- await ctx.execSubAgent({- 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] execSubAgent 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,- };- };--export const execSubAgents =- (ctx: RuntimeExecutorContext): InstructionExecutor =>- 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);-- if (state.metadata?.isSubAgent === true) {- log('[%s] Nested sub-agent batch dispatch blocked', taskLogId);- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- results: tasks.map((task) => ({- description: task.description,- error: 'Sub-agent calls cannot be triggered from within another sub-agent.',- success: false,- taskMessageId: parentMessageId,- threadId: '',- })),- },- phase: 'sub_agents_batch_result',- session: {- messageCount: state.messages.length,- sessionId: operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as unknown as AgentRuntimeContext,- };- }-- 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: '',- groupId: state.metadata?.groupId ?? undefined,- 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.execSubAgent && topicId && agentId) {- try {- await ctx.execSubAgent({- 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,- };- };diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 203409b3f73..655929a4b9b 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -711,7 +711,7 @@ export class GeneralChatAgent implements Agent {// Single sub-agent completed, continue to call LLM with resultconst { parentMessageId } = context.payload as SubAgentResultPayload;- // Continue to call LLM with updated messages (task message is already in state)+ // Continue to call LLM with the latest state after the sub-agent run.return this.toLLMCall({messages: state.messages,@@ -732,9 +732,9 @@ export class GeneralChatAgent implements Agent {return { reason: 'queued_message_interrupt', type: 'finish' };}- // Inject a virtual user message to force the model to summarize or continue+ // Inject a virtual user message to force the model to summarize or continue.// This fixes an issue where some models (e.g., Kimi K2) return empty content- // when the last message is a task result, thinking the task is already done+ // when the last message is a sub-agent result, thinking the task is already done.const messagesWithPrompt = [...state.messages,{@@ -744,7 +744,7 @@ export class GeneralChatAgent implements Agent {},];- // Continue to call LLM with updated messages (task messages are already in state)+ // Continue to call LLM with the latest state after the sub-agent runs.return this.toLLMCall({messages: messagesWithPrompt,diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 16345a72ce2..26f5327436d 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -1663,7 +1663,7 @@ describe('GeneralChatAgent', () => {messages: [{ role: 'user', content: 'Execute task' },{ role: 'assistant', content: '' },- { role: 'task', content: 'Task result', metadata: { instruction: 'Do task' } },+ { role: 'tool', content: 'Task result', tool_call_id: 'call-sub-agent-1' },] as any,});@@ -1671,7 +1671,6 @@ describe('GeneralChatAgent', () => {parentMessageId: 'task-parent-msg',result: {success: true,- taskMessageId: 'task-1',threadId: 'thread-1',result: 'Task result',},@@ -1702,7 +1701,7 @@ describe('GeneralChatAgent', () => {messages: [{ role: 'user', content: 'Execute task' },{ role: 'assistant', content: '' },- { role: 'task', content: 'Task failed: timeout', metadata: { instruction: 'Do task' } },+ { role: 'tool', content: 'Task failed: timeout', tool_call_id: 'call-sub-agent-1' },] as any,});@@ -1710,7 +1709,6 @@ describe('GeneralChatAgent', () => {parentMessageId: 'task-parent-msg',result: {success: false,- taskMessageId: 'task-1',threadId: 'thread-1',error: 'Task timeout after 1800000ms',},@@ -1737,7 +1735,7 @@ describe('GeneralChatAgent', () => {messages: [{ role: 'user', content: 'Execute task' },{ role: 'assistant', content: '' },- { role: 'task', content: 'Task result', metadata: { instruction: 'Do task' } },+ { role: 'tool', content: 'Task result', tool_call_id: 'call-sub-agent-1' },] as any,});@@ -1763,16 +1761,16 @@ describe('GeneralChatAgent', () => {messages: [{ role: 'user', content: 'Execute tasks' },{ role: 'assistant', content: '' },- { role: 'task', content: 'Task 1 result', metadata: { instruction: 'Do task 1' } },- { role: 'task', content: 'Task 2 result', metadata: { instruction: 'Do task 2' } },+ { role: 'tool', content: 'Task 1 result', tool_call_id: 'call-sub-agent-1' },+ { role: 'tool', content: 'Task 2 result', tool_call_id: 'call-sub-agent-2' },] as any,});const context = createMockContext('sub_agents_batch_result', {parentMessageId: 'task-parent-msg',results: [- { success: true, taskMessageId: 'task-1', threadId: 'thread-1', result: 'Task 1 result' },- { success: true, taskMessageId: 'task-2', threadId: 'thread-2', result: 'Task 2 result' },+ { success: true, threadId: 'thread-1', result: 'Task 1 result' },+ { success: true, threadId: 'thread-2', result: 'Task 2 result' },],});@@ -1808,18 +1806,17 @@ describe('GeneralChatAgent', () => {messages: [{ role: 'user', content: 'Execute tasks' },{ role: 'assistant', content: '' },- { role: 'task', content: 'Task 1 result', metadata: { instruction: 'Do task 1' } },- { role: 'task', content: 'Task failed: timeout', metadata: { instruction: 'Do task 2' } },+ { role: 'tool', content: 'Task 1 result', tool_call_id: 'call-sub-agent-1' },+ { role: 'tool', content: 'Task failed: timeout', tool_call_id: 'call-sub-agent-2' },] as any,});const context = createMockContext('sub_agents_batch_result', {parentMessageId: 'task-parent-msg',results: [- { success: true, taskMessageId: 'task-1', threadId: 'thread-1', result: 'Task 1 result' },+ { success: true, threadId: 'thread-1', result: 'Task 1 result' },{success: false,- taskMessageId: 'task-2',threadId: 'thread-2',error: 'Task timeout after 1800000ms',},@@ -1854,8 +1851,8 @@ describe('GeneralChatAgent', () => {messages: [{ role: 'user', content: 'Execute tasks' },{ role: 'assistant', content: '' },- { role: 'task', content: 'Task 1 result', metadata: { instruction: 'Do task 1' } },- { role: 'task', content: 'Task 2 result', metadata: { instruction: 'Do task 2' } },+ { role: 'tool', content: 'Task 1 result', tool_call_id: 'call-sub-agent-1' },+ { role: 'tool', content: 'Task 2 result', tool_call_id: 'call-sub-agent-2' },] as any,});diff --git a/packages/agent-runtime/src/executors/index.ts b/packages/agent-runtime/src/executors/index.tsindex 02472d82247..0017452506d 100644--- a/packages/agent-runtime/src/executors/index.ts+++ b/packages/agent-runtime/src/executors/index.ts@@ -1,4 +1,5 @@export * from './finish';export * from './humanApprove';export * from './resolveTools';+export * from './subAgent';export * from './tool';diff --git a/packages/agent-runtime/src/executors/subAgent.test.ts b/packages/agent-runtime/src/executors/subAgent.test.tsnew file mode 100644index 00000000000..8c52fa89088--- /dev/null+++ b/packages/agent-runtime/src/executors/subAgent.test.ts@@ -0,0 +1,247 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { AgentRuntimeHost } from '../transport';+import type { AgentInstruction, AgentState, SubAgentTask } from '../types';+import { execSubAgent, execSubAgents } from './subAgent';++interface TargetSubAgentTask extends SubAgentTask {+ targetAgentId: string;+}++const createState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: {+ calculatedAt: '2026-07-09T00:00:00.000Z',+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt: '2026-07-09T00:00:00.000Z',+ lastModified: '2026-07-09T00:00:00.000Z',+ maxSteps: 100,+ messages: [],+ metadata: {+ agentId: 'parent-agent',+ threadId: 'thread-1',+ topicId: 'topic-1',+ },+ operationId: 'op-1',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ },+ ...overrides,+});++describe('sub-agent executors', () => {+ let execSubAgentTransport: ReturnType<typeof vi.fn>;+ let update: ReturnType<typeof vi.fn>;+ let host: AgentRuntimeHost;++ beforeEach(() => {+ execSubAgentTransport = vi.fn().mockResolvedValue({+ assistantMessageId: 'assistant-child',+ operationId: 'child-op',+ success: true,+ threadId: 'child-thread',+ });+ update = vi.fn().mockResolvedValue(undefined);++ host = {+ operation: {+ operationId: 'op-1',+ stepIndex: 2,+ topicId: 'topic-1',+ },+ transports: {+ messages: {+ createAssistantMessage: vi.fn(),+ createToolMessage: vi.fn(),+ deleteMessage: vi.fn(),+ findById: vi.fn(),+ query: vi.fn(),+ update,+ updatePluginState: vi.fn(),+ updateToolMessage: vi.fn(),+ },+ stream: {+ publishChunk: vi.fn(),+ publishError: vi.fn(),+ publishEvent: vi.fn(),+ },+ subAgent: {+ execSubAgent: execSubAgentTransport,+ execVirtualSubAgent: vi.fn(),+ },+ },+ } as unknown as AgentRuntimeHost;+ });++ it('dispatches target agent with the source parent message and advances to sub_agent_result', async () => {+ const instruction: Extract<AgentInstruction, { type: 'exec_sub_agent' }> = {+ payload: {+ parentMessageId: 'tool-msg-1',+ task: {+ description: 'Call target',+ instruction: 'Do useful work',+ targetAgentId: 'target-agent',+ timeout: 1_800_000,+ } as TargetSubAgentTask,+ },+ type: 'exec_sub_agent',+ };++ const result = await execSubAgent(host)(instruction, createState());++ expect(execSubAgentTransport).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'target-agent',+ instruction: 'Do useful work',+ parentMessageId: 'tool-msg-1',+ parentOperationId: 'op-1',+ timeout: 1_800_000,+ title: 'Call target',+ topicId: 'topic-1',+ }),+ );+ expect(result.nextContext?.phase).toBe('sub_agent_result');+ expect(result.nextContext?.payload).toMatchObject({+ parentMessageId: 'tool-msg-1',+ result: {+ success: true,+ threadId: 'child-thread',+ },+ });+ });++ it('blocks nested sub-agent dispatch before transport dispatch', async () => {+ const instruction: Extract<AgentInstruction, { type: 'exec_sub_agent' }> = {+ payload: {+ parentMessageId: 'tool-msg-1',+ task: {+ description: 'Nested',+ instruction: 'Do nested work',+ },+ },+ type: 'exec_sub_agent',+ };++ const result = await execSubAgent(host)(+ instruction,+ createState({ metadata: { agentId: 'parent-agent', isSubAgent: true, topicId: 'topic-1' } }),+ );++ expect(execSubAgentTransport).not.toHaveBeenCalled();+ expect(result.nextContext?.payload).toMatchObject({+ result: {+ error: 'Sub-agent calls cannot be triggered from within another sub-agent.',+ success: false,+ },+ });+ });++ it('skips dispatch when no sub-agent transport is registered', async () => {+ const instruction: Extract<AgentInstruction, { type: 'exec_sub_agent' }> = {+ payload: {+ parentMessageId: 'tool-msg-1',+ task: {+ description: 'Call target',+ instruction: 'Do work',+ },+ },+ type: 'exec_sub_agent',+ };++ const result = await execSubAgent({+ ...host,+ transports: {+ ...host.transports,+ subAgent: undefined,+ },+ })(instruction, createState());++ expect(execSubAgentTransport).not.toHaveBeenCalled();+ expect(result.nextContext?.payload).toMatchObject({+ parentMessageId: 'tool-msg-1',+ result: { success: false, threadId: '' },+ });+ });++ it('reports dispatch failures through the result payload', async () => {+ execSubAgentTransport.mockRejectedValueOnce(new Error('spawn failed'));+ const instruction: Extract<AgentInstruction, { type: 'exec_sub_agent' }> = {+ payload: {+ parentMessageId: 'tool-msg-1',+ task: {+ description: 'Call target',+ instruction: 'Do work',+ },+ },+ type: 'exec_sub_agent',+ };++ const result = await execSubAgent(host)(instruction, createState());++ expect(update).not.toHaveBeenCalled();+ expect(result.nextContext?.payload).toMatchObject({+ result: { success: false },+ });+ });++ it('dispatches a batch using the source parent message', async () => {+ execSubAgentTransport+ .mockResolvedValueOnce({+ assistantMessageId: 'assistant-child-1',+ operationId: 'child-op-1',+ success: true,+ threadId: 'child-thread-1',+ })+ .mockResolvedValueOnce({+ assistantMessageId: 'assistant-child-2',+ operationId: 'child-op-2',+ success: true,+ threadId: 'child-thread-2',+ });+ const instruction: Extract<AgentInstruction, { type: 'exec_sub_agents' }> = {+ payload: {+ parentMessageId: 'tool-msg-1',+ tasks: [+ { description: 'Task A', instruction: 'Do A' },+ {+ description: 'Task B',+ instruction: 'Do B',+ targetAgentId: 'target-b',+ } as TargetSubAgentTask,+ ],+ },+ type: 'exec_sub_agents',+ };++ const result = await execSubAgents(host)(instruction, createState());++ expect(execSubAgentTransport).toHaveBeenCalledTimes(2);+ expect(execSubAgentTransport).toHaveBeenLastCalledWith(+ expect.objectContaining({+ agentId: 'target-b',+ parentMessageId: 'tool-msg-1',+ }),+ );+ expect(result.nextContext?.phase).toBe('sub_agents_batch_result');+ expect(result.nextContext?.payload).toMatchObject({+ parentMessageId: 'tool-msg-1',+ results: [+ { success: true, threadId: 'child-thread-1' },+ { success: true, threadId: 'child-thread-2' },+ ],+ });+ });+});diff --git a/packages/agent-runtime/src/executors/subAgent.ts b/packages/agent-runtime/src/executors/subAgent.tsnew file mode 100644index 00000000000..e5cefbcfaba--- /dev/null+++ b/packages/agent-runtime/src/executors/subAgent.ts@@ -0,0 +1,187 @@+import type { AgentRuntimeHost } from '../transport';+import type {+ AgentEvent,+ AgentInstructionExecSubAgent,+ AgentInstructionExecSubAgents,+ AgentRuntimeContext,+ AgentState,+ InstructionExecutor,+ SubAgentTask,+} from '../types';++interface SubAgentTaskWithTarget extends SubAgentTask {+ targetAgentId?: string;+}++const createSessionContext = (state: AgentState, operationId: string) => ({+ messageCount: state.messages.length,+ sessionId: operationId,+ status: 'running' as const,+ stepCount: state.stepCount + 1,+});++const createNestedSingleResult = (+ state: AgentState,+ operationId: string,+ parentMessageId: string,+): AgentRuntimeContext =>+ ({+ payload: {+ parentMessageId,+ result: {+ error: 'Sub-agent calls cannot be triggered from within another sub-agent.',+ success: false,+ threadId: '',+ },+ },+ phase: 'sub_agent_result',+ session: createSessionContext(state, operationId),+ }) as AgentRuntimeContext;++const createNestedBatchResult = (+ state: AgentState,+ operationId: string,+ parentMessageId: string,+ tasks: SubAgentTask[],+): AgentRuntimeContext =>+ ({+ payload: {+ parentMessageId,+ results: tasks.map((task) => ({+ description: task.description,+ error: 'Sub-agent calls cannot be triggered from within another sub-agent.',+ success: false,+ threadId: '',+ })),+ },+ phase: 'sub_agents_batch_result',+ session: createSessionContext(state, operationId),+ }) as AgentRuntimeContext;++const resolveTaskAgentId = (task: SubAgentTask, fallbackAgentId?: string) =>+ (task as SubAgentTaskWithTarget).targetAgentId ?? fallbackAgentId;++export const execSubAgent =+ (host: AgentRuntimeHost): InstructionExecutor =>+ async (instruction, state) => {+ const { payload } = instruction as AgentInstructionExecSubAgent;+ const { parentMessageId, task } = payload;+ const events: AgentEvent[] = [];+ const { operationId } = host.operation;++ const topicId = host.operation.topicId ?? state.metadata?.topicId;+ const agentId = state.metadata?.agentId;+ const targetAgentId = resolveTaskAgentId(task, agentId);++ if (state.metadata?.isSubAgent === true) {+ return {+ events,+ newState: state,+ nextContext: createNestedSingleResult(state, operationId, parentMessageId),+ };+ }++ let dispatched = false;+ let threadId = '';++ if (host.transports.subAgent && topicId && agentId && targetAgentId) {+ try {+ const dispatchResult = await host.transports.subAgent.execSubAgent({+ agentId: targetAgentId,+ groupId: state.metadata?.groupId ?? undefined,+ instruction: task.instruction,+ parentMessageId,+ parentOperationId: operationId,+ timeout: task.timeout,+ title: task.description,+ topicId,+ });+ dispatched = dispatchResult.success;+ threadId = dispatchResult.threadId ?? '';+ } catch {+ // Dispatch failures are reported in the sub_agent_result payload.+ }+ }++ return {+ events,+ newState: state,+ nextContext: {+ payload: {+ parentMessageId,+ result: {+ success: dispatched,+ threadId,+ },+ },+ phase: 'sub_agent_result',+ session: createSessionContext(state, operationId),+ } as AgentRuntimeContext,+ };+ };++export const execSubAgents =+ (host: AgentRuntimeHost): InstructionExecutor =>+ async (instruction, state) => {+ const { payload } = instruction as AgentInstructionExecSubAgents;+ const { parentMessageId, tasks } = payload;+ const events: AgentEvent[] = [];+ const { operationId } = host.operation;++ const topicId = host.operation.topicId ?? state.metadata?.topicId;+ const agentId = state.metadata?.agentId;++ if (state.metadata?.isSubAgent === true) {+ return {+ events,+ newState: state,+ nextContext: createNestedBatchResult(state, operationId, parentMessageId, tasks),+ };+ }++ const taskResults: Array<{ success: boolean; threadId: string }> = [];++ for (const task of tasks) {+ const targetAgentId = resolveTaskAgentId(task, agentId);++ let taskDispatched = false;+ let threadId = '';++ if (host.transports.subAgent && topicId && agentId && targetAgentId) {+ try {+ const dispatchResult = await host.transports.subAgent.execSubAgent({+ agentId: targetAgentId,+ groupId: state.metadata?.groupId ?? undefined,+ instruction: task.instruction,+ parentMessageId,+ parentOperationId: operationId,+ timeout: task.timeout,+ title: task.description,+ topicId,+ });+ taskDispatched = dispatchResult.success;+ threadId = dispatchResult.threadId ?? '';+ } catch {+ // Dispatch failures are reported in the batch result payload.+ }+ }++ taskResults.push({+ success: taskDispatched,+ threadId,+ });+ }++ return {+ events,+ newState: state,+ nextContext: {+ payload: {+ parentMessageId,+ results: taskResults,+ },+ phase: 'sub_agents_batch_result',+ session: createSessionContext(state, operationId),+ } as AgentRuntimeContext,+ };+ };diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.tsindex d92b8ace7c7..649f7d2e7ff 100644--- a/packages/agent-runtime/src/types/instruction.ts+++ b/packages/agent-runtime/src/types/instruction.ts@@ -190,8 +190,6 @@ export interface SubAgentResultPayload {result?: string;/** Whether the sub-agent completed successfully */success: boolean;- /** Sub-agent message ID */- taskMessageId: string;/** Thread ID where the sub-agent was executed */threadId: string;};@@ -211,8 +209,6 @@ export interface SubAgentsBatchResultPayload {result?: string;/** Whether the sub-agent completed successfully */success: boolean;- /** Sub-agent message ID */- taskMessageId: string;/** Thread ID where the sub-agent was executed */threadId: string;}>;diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.tsindex cbee950e666..bd7c7073bdd 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.ts@@ -36,9 +36,6 @@ describe('exec_sub_agent executor', () => {);const state = createInitialState({ operationId: 'test-op' });- // Mock task message creation- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-// Mock task executionmockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',@@ -70,7 +67,10 @@ describe('exec_sub_agent executor', () => {expect(payload.result).toBeDefined();expect(payload.result.success).toBe(true);expect(payload.result.threadId).toBe('thread_1');- expect(payload.result.taskMessageId).toBe('task_msg_1');+ expect(mockExecSubAgentTask).toHaveBeenCalledWith(+ expect.objectContaining({ parentMessageId: 'msg_parent' }),+ );+ expect(mockStore.optimisticCreateMessage).not.toHaveBeenCalled();});});@@ -79,7 +79,7 @@ describe('exec_sub_agent executor', () => {// Givenconst mockStore = createMockStore();const context = createTestContext({ agentId: undefined, topicId: null });- const instruction = createExecSubAgentInstruction();+ const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');const state = createInitialState({ operationId: 'test-op' });// Override operation context to have no agentId/topicId@@ -112,40 +112,13 @@ describe('exec_sub_agent executor', () => {expect(payload.result.error).toBe('No valid context available');});- it('should handle task message creation failure', async () => {- // Given- const mockStore = createMockStore();- const context = createTestContext();- const instruction = createExecSubAgentInstruction();- const state = createInitialState({ operationId: 'test-op' });-- // Mock task message creation failure- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce(null);-- // When- const result = await executeWithMockContext({- context,- executor: 'exec_sub_agent',- instruction,- mockStore,- state,- });-- // Then- const payload = (result.nextContext as AgentRuntimeContext).payload as SubAgentResultPayload;- expect(payload.result.success).toBe(false);- expect(payload.result.error).toBe('Failed to create task message');- });-it('should handle task creation API failure', async () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentInstruction();+ const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');const state = createInitialState({ operationId: 'test-op' });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: '',error: 'API error',@@ -168,7 +141,7 @@ describe('exec_sub_agent executor', () => {expect(payload.result.success).toBe(false);expect(payload.result.error).toBe('API error');expect(mockStore.optimisticUpdateMessageContent).toHaveBeenCalledWith(- 'task_msg_1',+ 'msg_parent','Task creation failed: API error',undefined,{ operationId: 'test-op' },@@ -179,11 +152,9 @@ describe('exec_sub_agent executor', () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentInstruction();+ const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');const state = createInitialState({ operationId: 'test-op' });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -213,15 +184,13 @@ describe('exec_sub_agent executor', () => {});describe('Task Status Polling', () => {- it('should update task message with taskDetail when completed', async () => {+ it('should update the source tool message with taskDetail when completed', async () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentInstruction();+ const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');const state = createInitialState({ operationId: 'test-op' });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -248,7 +217,7 @@ describe('exec_sub_agent executor', () => {// Thenexpect(mockStore.internal_dispatchMessage).toHaveBeenCalledWith({- id: 'task_msg_1',+ id: 'msg_parent',type: 'updateMessage',value: { taskDetail: { status: 'completed' } },},@@ -262,11 +231,9 @@ describe('exec_sub_agent executor', () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentInstruction();+ const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');const state = createInitialState({ operationId: 'test-op' });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -293,7 +260,7 @@ describe('exec_sub_agent executor', () => {expect(payload.result.success).toBe(false);expect(payload.result.error).toBe('Task was cancelled');expect(mockStore.optimisticUpdateMessageContent).toHaveBeenCalledWith(- 'task_msg_1',+ 'msg_parent','Task was cancelled',undefined,{ operationId: 'test-op' },@@ -308,11 +275,9 @@ describe('exec_sub_agent executor', () => {// Use same operationId for both context and stateconst operationId = 'test-op';const context = createTestContext({ operationId });- const instruction = createExecSubAgentInstruction();+ const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');const state = createInitialState({ operationId });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-// Mock execSubAgentTask to mark operation as cancelled after it's called// This simulates cancellation happening right after task creation but before pollingmockExecSubAgentTask.mockImplementation(async () => {@@ -356,8 +321,6 @@ describe('exec_sub_agent executor', () => {);const state = createInitialState({ operationId: 'test-op', stepCount: 5 });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -394,14 +357,12 @@ describe('exec_sub_agent executor', () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentInstruction();+ const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');const state = createInitialState({ messages: [], operationId: 'test-op' });const updatedMessages = [{ content: 'test', id: 'msg_1', role: 'user' }];mockStore.dbMessagesMap[context.messageKey] = updatedMessages as any;- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -427,53 +388,4 @@ describe('exec_sub_agent executor', () => {expect(result.newState.messages).toEqual(updatedMessages);});});-- describe('Task Message Creation', () => {- it('should create task message with correct parameters', async () => {- // Given- const mockStore = createMockStore();- const context = createTestContext({ agentId: 'agent_1', topicId: 'topic_1' });- const instruction = createExecSubAgentInstruction(- { description: 'Test task', instruction: 'Do something important' },- 'msg_parent',- );- const state = createInitialState({ operationId: 'test-op' });-- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-- mockExecSubAgentTask.mockResolvedValueOnce({- assistantMessageId: 'asst_1',- operationId: 'op_1',- success: true,- threadId: 'thread_1',- });-- mockGetSubAgentTaskStatus.mockResolvedValueOnce({- result: 'Done',- status: 'completed',- });-- // When- await executeWithMockContext({- context,- executor: 'exec_sub_agent',- instruction,- mockStore,- state,- });-- // Then- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(- {- agentId: 'agent_1',- content: '',- metadata: { instruction: 'Do something important', taskTitle: 'Test task' },- parentId: 'msg_parent',- role: 'task',- topicId: 'topic_1',- },- { operationId: 'test-op' },- );- });- });});diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.tsindex c2400e4c5a2..8f02bcf9b4c 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.ts@@ -39,9 +39,6 @@ describe('exec_sub_agents executor', () => {);const state = createInitialState({ operationId: 'test-op' });- // Mock task message creation- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-// Mock task executionmockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',@@ -74,7 +71,10 @@ describe('exec_sub_agents executor', () => {expect(payload.results).toHaveLength(1);expect(payload.results[0].success).toBe(true);expect(payload.results[0].threadId).toBe('thread_1');- expect(payload.results[0].taskMessageId).toBe('task_msg_1');+ expect(mockExecSubAgentTask).toHaveBeenCalledWith(+ expect.objectContaining({ parentMessageId: 'msg_parent' }),+ );+ expect(mockStore.optimisticCreateMessage).not.toHaveBeenCalled();});it('should execute multiple tasks in parallel', async () => {@@ -91,12 +91,6 @@ describe('exec_sub_agents executor', () => {);const state = createInitialState({ operationId: 'test-op' });- // Mock task message creation for each task- (mockStore.optimisticCreateMessage as Mock)- .mockResolvedValueOnce({ id: 'task_msg_1' })- .mockResolvedValueOnce({ id: 'task_msg_2' })- .mockResolvedValueOnce({ id: 'task_msg_3' });-// Mock task execution for each taskmockExecSubAgentTask.mockResolvedValueOnce({@@ -147,7 +141,7 @@ describe('exec_sub_agents executor', () => {// Givenconst mockStore = createMockStore();const context = createTestContext({ agentId: undefined, topicId: null });- const instruction = createExecSubAgentsInstruction();+ const instruction = createExecSubAgentsInstruction([], 'msg_parent');const state = createInitialState({ operationId: 'test-op' });// Override operation context to have no agentId/topicId@@ -182,41 +176,13 @@ describe('exec_sub_agents executor', () => {expect(payload.results[0].error).toBe('No valid context available');});- it('should handle task message creation failure', async () => {- // Given- const mockStore = createMockStore();- const context = createTestContext();- const instruction = createExecSubAgentsInstruction();- const state = createInitialState({ operationId: 'test-op' });-- // Mock task message creation failure- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce(null);-- // When- const result = await executeWithMockContext({- context,- executor: 'exec_sub_agents',- instruction,- mockStore,- state,- });-- // Then- const payload = (result.nextContext as AgentRuntimeContext)- .payload as SubAgentsBatchResultPayload;- expect(payload.results[0].success).toBe(false);- expect(payload.results[0].error).toBe('Failed to create task message');- });-it('should handle task creation API failure', async () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentsInstruction();+ const instruction = createExecSubAgentsInstruction([], 'msg_parent');const state = createInitialState({ operationId: 'test-op' });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: '',error: 'API error',@@ -240,8 +206,8 @@ describe('exec_sub_agents executor', () => {expect(payload.results[0].success).toBe(false);expect(payload.results[0].error).toBe('API error');expect(mockStore.optimisticUpdateMessageContent).toHaveBeenCalledWith(- 'task_msg_1',- 'Task creation failed: API error',+ 'msg_parent',+ '1. Test task\nFailed: API error',undefined,{ operationId: 'test-op' },);@@ -251,11 +217,9 @@ describe('exec_sub_agents executor', () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentsInstruction();+ const instruction = createExecSubAgentsInstruction([], 'msg_parent');const state = createInitialState({ operationId: 'test-op' });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -286,15 +250,13 @@ describe('exec_sub_agents executor', () => {});describe('Task Status Polling', () => {- it('should update task message with taskDetail when completed', async () => {+ it('should update the source tool message with taskDetail when completed', async () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentsInstruction();+ const instruction = createExecSubAgentsInstruction([], 'msg_parent');const state = createInitialState({ operationId: 'test-op' });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -321,7 +283,7 @@ describe('exec_sub_agents executor', () => {// Thenexpect(mockStore.internal_dispatchMessage).toHaveBeenCalledWith({- id: 'task_msg_1',+ id: 'msg_parent',type: 'updateMessage',value: { taskDetail: { status: 'completed' } },},@@ -336,11 +298,9 @@ describe('exec_sub_agents executor', () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentsInstruction();+ const instruction = createExecSubAgentsInstruction([], 'msg_parent');const state = createInitialState({ operationId: 'test-op' });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -368,8 +328,8 @@ describe('exec_sub_agents executor', () => {expect(payload.results[0].success).toBe(false);expect(payload.results[0].error).toBe('Task was cancelled');expect(mockStore.optimisticUpdateMessageContent).toHaveBeenCalledWith(- 'task_msg_1',- 'Task was cancelled',+ 'msg_parent',+ '1. Test task\nFailed: Task was cancelled',undefined,{ operationId: 'test-op' },);@@ -383,11 +343,9 @@ describe('exec_sub_agents executor', () => {// Use same operationId for both context and stateconst operationId = 'test-op';const context = createTestContext({ operationId });- const instruction = createExecSubAgentsInstruction();+ const instruction = createExecSubAgentsInstruction([], 'msg_parent');const state = createInitialState({ operationId });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-// Mock execSubAgentTask to mark operation as cancelled after it's called// This simulates cancellation happening right after task creation but before pollingmockExecSubAgentTask.mockImplementation(async () => {@@ -433,8 +391,6 @@ describe('exec_sub_agents executor', () => {);const state = createInitialState({ operationId: 'test-op', stepCount: 5 });- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -471,14 +427,12 @@ describe('exec_sub_agents executor', () => {// Givenconst mockStore = createMockStore();const context = createTestContext();- const instruction = createExecSubAgentsInstruction();+ const instruction = createExecSubAgentsInstruction([], 'msg_parent');const state = createInitialState({ messages: [], operationId: 'test-op' });const updatedMessages = [{ content: 'test', id: 'msg_1', role: 'user' }];mockStore.dbMessagesMap[context.messageKey] = updatedMessages as any;- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',operationId: 'op_1',@@ -505,56 +459,6 @@ describe('exec_sub_agents executor', () => {});});- describe('Task Message Creation', () => {- it('should create task message with correct parameters', async () => {- // Given- const mockStore = createMockStore();- const context = createTestContext({ agentId: 'agent_1', topicId: 'topic_1' });- const instruction = createExecSubAgentsInstruction(- [{ description: 'Test task', instruction: 'Do something important' }],- 'msg_parent',- );- const state = createInitialState({ operationId: 'test-op' });-- (mockStore.optimisticCreateMessage as Mock).mockResolvedValueOnce({ id: 'task_msg_1' });-- mockExecSubAgentTask.mockResolvedValueOnce({- assistantMessageId: 'asst_1',- operationId: 'op_1',- success: true,- threadId: 'thread_1',- });-- mockGetSubAgentTaskStatus.mockResolvedValueOnce({- result: 'Done',- status: 'completed',- });-- // When- await executeWithMockContext({- context,- executor: 'exec_sub_agents',- instruction,- mockStore,- state,- });-- // Then- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(- {- agentId: 'agent_1',- content: '',- createdAt: expect.any(Number),- metadata: { instruction: 'Do something important' },- parentId: 'msg_parent',- role: 'task',- topicId: 'topic_1',- },- { operationId: 'test-op' },- );- });- });-describe('Mixed Results', () => {it('should handle mix of successful and failed tasks', async () => {// Given@@ -569,10 +473,6 @@ describe('exec_sub_agents executor', () => {);const state = createInitialState({ operationId: 'test-op' });- (mockStore.optimisticCreateMessage as Mock)- .mockResolvedValueOnce({ id: 'task_msg_1' })- .mockResolvedValueOnce({ id: 'task_msg_2' });-mockExecSubAgentTask.mockResolvedValueOnce({assistantMessageId: 'asst_1',diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.tsindex b7fbd0cfccf..1fc664adaa8 100644--- a/src/store/chat/agents/createAgentExecutors.ts+++ b/src/store/chat/agents/createAgentExecutors.ts@@ -15,6 +15,7 @@ import type {InstructionExecutor,SubAgentResultPayload,SubAgentsBatchResultPayload,+ SubAgentTask,} from '@lobechat/agent-runtime';import { UsageCounter } from '@lobechat/agent-runtime';import { countContextTokens, type ToolsEngine } from '@lobechat/context-engine';@@ -127,6 +128,21 @@ const localizeError = (error: ChatMessageError): ChatMessageError => {return error;};+const formatSubAgentBatchResultContent = (+ tasks: SubAgentTask[],+ results: SubAgentsBatchResultPayload['results'],+) =>+ results+ .map((result, index) => {+ const title = tasks[index]?.description ?? `Task ${index + 1}`;+ const content = result.success+ ? (result.result ?? 'Completed successfully.')+ : `Failed: ${result.error ?? 'Unknown error'}`;++ return `${index + 1}. ${title}\n${content}`;+ })+ .join('\n\n');+/*** Creates custom executors for the Chat Agent Runtime* These executors wrap existing chat store methods to integrate with agent-runtime@@ -1306,11 +1322,10 @@ export const createAgentExecutors = (context: {* Dispatches a single sub-agent** Flow:- * 1. Create a task message (role: 'task') as placeholder- * 2. Call execSubAgentTask API (backend creates thread)- * 3. Poll for sub-agent completion- * 4. Update task message content with result on completion- * 5. Return sub_agent_result phase with result+ * 1. Call execSubAgentTask API (backend creates thread)+ * 2. Poll for sub-agent completion+ * 3. Update the source tool message with result on completion+ * 4. Return sub_agent_result phase with result*/exec_sub_agent: async (instruction, state) => {const { parentMessageId, task } = (instruction as AgentInstructionExecSubAgent).payload;@@ -1339,7 +1354,6 @@ export const createAgentExecutors = (context: {result: {error: 'No valid context available',success: false,- taskMessageId: '',threadId: '',},} as SubAgentResultPayload,@@ -1366,63 +1380,16 @@ export const createAgentExecutors = (context: {const taskLogId = `${sessionLogId}:task`;try {- // 1. Create task message as placeholder- // IMPORTANT: Use operation context's agentId (current agent) for message creation- // This ensures the task message appears in the current conversation- const taskMessageResult = await context.get().optimisticCreateMessage(- {- agentId, // Use current agent's ID (not targetAgentId)- content: '',- metadata: {- instruction: task.instruction,- taskTitle: task.description,- // Store targetAgentId in metadata for UI display- ...(targetAgentId && { targetAgentId }),- },- parentId: parentMessageId,- role: 'task',- topicId,- },- { operationId: state.operationId },- );-- if (!taskMessageResult) {- log('[%s] Failed to create task message', taskLogId);- return {- events,- newState: state,- nextContext: {- payload: {- parentMessageId,- result: {- error: 'Failed to create task message',- success: false,- taskMessageId: '',- threadId: '',- },- } as SubAgentResultPayload,- phase: 'sub_agent_result',- session: {- messageCount: state.messages.length,- sessionId: state.operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- } as AgentRuntimeContext,- };- }-- const taskMessageId = taskMessageResult.id;- log('[%s] Created task message: %s', taskLogId, taskMessageId);+ const resultMessageId = parentMessageId;- // 2. Create and execute task on server+ // 1. Create and execute task on server// IMPORTANT: Use executionAgentId here (targetAgentId if in callAgent mode)// This ensures the task executes with the correct agent's configlog('[%s] Using server-side execution with agentId: %s', taskLogId, executionAgentId);const createResult = await aiAgentService.execSubAgentTask({agentId: executionAgentId, // Use targetAgentId for callAgent, or current agentId for sub-agent dispatchinstruction: task.instruction,- parentMessageId: taskMessageId,+ parentMessageId: resultMessageId,title: task.description,topicId,});@@ -1432,7 +1399,7 @@ export const createAgentExecutors = (context: {await context.get().optimisticUpdateMessageContent(- taskMessageId,+ resultMessageId,`Task creation failed: ${createResult.error}`,undefined,{ operationId: state.operationId },@@ -1446,7 +1413,6 @@ export const createAgentExecutors = (context: {result: {error: createResult.error,success: false,- taskMessageId,threadId: '',},} as SubAgentResultPayload,@@ -1463,7 +1429,7 @@ export const createAgentExecutors = (context: {log('[%s] Task created with threadId: %s', taskLogId, createResult.threadId);- // 3. Poll for task completion+ // 2. Poll for task completionconst pollInterval = 3000; // 3 secondsconst maxWait = task.timeout || 1_800_000; // Default 30 minutesconst startTime = Date.now();@@ -1482,11 +1448,11 @@ export const createAgentExecutors = (context: {log('[%s] Failed to interrupt cancelled task: %O', taskLogId, err);}- // Update task message to cancelled state+ // Update the source tool message to cancelled state.await context.get().optimisticUpdateMessageContent(- taskMessageId,+ resultMessageId,'Task was cancelled by user.',undefined,{ operationId: state.operationId },@@ -1502,7 +1468,6 @@ export const createAgentExecutors = (context: {result: {error: 'Operation cancelled',success: false,- taskMessageId,threadId: createResult.threadId,},} as SubAgentResultPayload,@@ -1521,17 +1486,17 @@ export const createAgentExecutors = (context: {threadId: createResult.threadId,});- // Update taskDetail in message if available+ // Update taskDetail on the source tool message if available.if (status.taskDetail) {context.get().internal_dispatchMessage({- id: taskMessageId,+ id: resultMessageId,type: 'updateMessage',value: { taskDetail: status.taskDetail },},{ operationId: state.operationId },);- log('[%s] Updated task message with taskDetail', taskLogId);+ log('[%s] Updated source tool message with taskDetail', taskLogId);}if (status.status === 'completed') {@@ -1539,7 +1504,7 @@ export const createAgentExecutors = (context: {if (status.result) {await context.get()- .optimisticUpdateMessageContent(taskMessageId, status.result, undefined, {+ .optimisticUpdateMessageContent(resultMessageId, status.result, undefined, {operationId: state.operationId,});}@@ -1553,7 +1518,6 @@ export const createAgentExecutors = (context: {result: {result: status.result,success: true,- taskMessageId,threadId: createResult.threadId,},} as SubAgentResultPayload,@@ -1575,7 +1539,7 @@ export const createAgentExecutors = (context: {await context.get().optimisticUpdateMessageContent(- taskMessageId,+ resultMessageId,`Task failed: ${errorMessage}`,undefined,{ operationId: state.operationId },@@ -1590,7 +1554,6 @@ export const createAgentExecutors = (context: {result: {error: status.error,success: false,- taskMessageId,threadId: createResult.threadId,},} as SubAgentResultPayload,@@ -1608,10 +1571,10 @@ export const createAgentExecutors = (context: {if (status.status === 'cancel') {log('[%s] Task was cancelled', taskLogId);// Note: Don't fail the operation here - it was cancelled intentionally- // The cancel handler already updated the message+ // The source tool message update records the cancellation.await context.get()- .optimisticUpdateMessageContent(taskMessageId, 'Task was cancelled', undefined, {+ .optimisticUpdateMessageContent(resultMessageId, 'Task was cancelled', undefined, {operationId: state.operationId,});const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];@@ -1624,7 +1587,6 @@ export const createAgentExecutors = (context: {result: {error: 'Task was cancelled',success: false,- taskMessageId,threadId: createResult.threadId,},} as SubAgentResultPayload,@@ -1657,7 +1619,7 @@ export const createAgentExecutors = (context: {await context.get().optimisticUpdateMessageContent(- taskMessageId,+ resultMessageId,`Task timeout after ${maxWait}ms`,undefined,{ operationId: state.operationId },@@ -1673,7 +1635,6 @@ export const createAgentExecutors = (context: {result: {error: `Task timeout after ${maxWait}ms`,success: false,- taskMessageId,threadId: createResult.threadId,},} as SubAgentResultPayload,@@ -1697,7 +1658,6 @@ export const createAgentExecutors = (context: {result: {error: error instanceof Error ? error.message : 'Unknown error',success: false,- taskMessageId: '',threadId: '',},} as SubAgentResultPayload,@@ -1718,11 +1678,10 @@ export const createAgentExecutors = (context: {* Dispatches one or more sub-agents in parallel** Flow:- * 1. For each sub-agent, create a task message (role: 'task') as placeholder- * 2. Call execSubAgentTask API (backend creates thread)- * 3. Poll for sub-agent completion- * 4. Update task message content with result on completion- * 5. Return sub_agents_batch_result phase with all results+ * 1. Call execSubAgentTask API for each task+ * 2. Poll for sub-agent completion+ * 3. Update the source tool message once with aggregated results+ * 4. Return sub_agents_batch_result phase with all results*/exec_sub_agents: async (instruction, state) => {const { parentMessageId, tasks } = (instruction as AgentInstructionExecSubAgents).payload;@@ -1747,7 +1706,6 @@ export const createAgentExecutors = (context: {results: tasks.map(() => ({error: 'No valid context available',success: false,- taskMessageId: '',threadId: '',})),} as SubAgentsBatchResultPayload,@@ -1770,65 +1728,30 @@ export const createAgentExecutors = (context: {log('[%s] Starting task: %s', taskLogId, task.description);try {- // 1. Create task message as placeholder- const taskMessageResult = await context.get().optimisticCreateMessage(- {- agentId,- content: '',- createdAt: Date.now() + taskIndex,- metadata: { instruction: task.instruction },- parentId: parentMessageId,- role: 'task',- topicId,- },- { operationId: state.operationId },- );-- if (!taskMessageResult) {- log('[%s] Failed to create task message', taskLogId);- return {- error: 'Failed to create task message',- success: false,- taskMessageId: '',- threadId: '',- };- }-- const taskMessageId = taskMessageResult.id;- log('[%s] Created task message: %s', taskLogId, taskMessageId);+ const resultMessageId = parentMessageId;- // 2. Create and execute task on server+ // 1. Create and execute task on serverlog('[%s] Using server-side execution', taskLogId);const createResult = await aiAgentService.execSubAgentTask({agentId,instruction: task.instruction,- parentMessageId: taskMessageId,+ parentMessageId: resultMessageId,title: task.description,topicId,});if (!createResult.success) {log('[%s] Failed to create task: %s', taskLogId, createResult.error);- // Update task message with error- await context- .get()- .optimisticUpdateMessageContent(- taskMessageId,- `Task creation failed: ${createResult.error}`,- undefined,- { operationId: state.operationId },- );return {error: createResult.error,success: false,- taskMessageId,threadId: '',};}log('[%s] Task created with threadId: %s', taskLogId, createResult.threadId);- // 4. Poll for task completion+ // 2. Poll for task completionconst pollInterval = 3000; // 3 secondsconst maxWait = task.timeout || 1_800_000; // Default 30 minutesconst startTime = Date.now();@@ -1847,20 +1770,9 @@ export const createAgentExecutors = (context: {log('[%s] Failed to interrupt cancelled task: %O', taskLogId, err);}- // Update task message to cancelled state- await context- .get()- .optimisticUpdateMessageContent(- taskMessageId,- 'Task was cancelled by user.',- undefined,- { operationId: state.operationId },- );-return {error: 'Operation cancelled',success: false,- taskMessageId,threadId: createResult.threadId,};}@@ -1869,33 +1781,24 @@ export const createAgentExecutors = (context: {threadId: createResult.threadId,});- // Update taskDetail in message if available+ // Update taskDetail on the source tool message if available.if (status.taskDetail) {context.get().internal_dispatchMessage({- id: taskMessageId,+ id: resultMessageId,type: 'updateMessage',value: { taskDetail: status.taskDetail },},{ operationId: state.operationId },);- log('[%s] Updated task message with taskDetail', taskLogId);+ log('[%s] Updated source tool message with taskDetail', taskLogId);}if (status.status === 'completed') {log('[%s] Task completed successfully', taskLogId);- // 5. Update task message with result- if (status.result) {- await context- .get()- .optimisticUpdateMessageContent(taskMessageId, status.result, undefined, {- operationId: state.operationId,- });- }return {result: status.result,success: true,- taskMessageId,threadId: createResult.threadId,};}@@ -1903,19 +1806,9 @@ export const createAgentExecutors = (context: {if (status.status === 'failed') {const errorMessage = status.error || 'Unknown error';log('[%s] Task failed: %s', taskLogId, errorMessage);- // Update task message with error- await context- .get()- .optimisticUpdateMessageContent(- taskMessageId,- `Task failed: ${errorMessage}`,- undefined,- { operationId: state.operationId },- );return {error: status.error,success: false,- taskMessageId,threadId: createResult.threadId,};}@@ -1923,16 +1816,10 @@ export const createAgentExecutors = (context: {if (status.status === 'cancel') {log('[%s] Task was cancelled', taskLogId);// Note: Don't fail the operation here - it was cancelled intentionally- // The cancel handler already updated the message- await context- .get()- .optimisticUpdateMessageContent(taskMessageId, 'Task was cancelled', undefined, {- operationId: state.operationId,- });+ // The aggregate result update below records the cancellation.return {error: 'Task was cancelled',success: false,- taskMessageId,threadId: createResult.threadId,};}@@ -1952,20 +1839,9 @@ export const createAgentExecutors = (context: {log('[%s] Failed to interrupt timed out task: %O', taskLogId, err);}- // Update task message with timeout error- await context- .get()- .optimisticUpdateMessageContent(- taskMessageId,- `Task timeout after ${maxWait}ms`,- undefined,- { operationId: state.operationId },- );-return {error: `Task timeout after ${maxWait}ms`,success: false,- taskMessageId,threadId: createResult.threadId,};} catch (error) {@@ -1973,7 +1849,6 @@ export const createAgentExecutors = (context: {return {error: error instanceof Error ? error.message : 'Unknown error',success: false,- taskMessageId: '',threadId: '',};}@@ -1983,6 +1858,15 @@ export const createAgentExecutors = (context: {log('[%s][exec_sub_agents] All tasks completed, results: %O', sessionLogId, results);+ await context+ .get()+ .optimisticUpdateMessageContent(+ parentMessageId,+ formatSubAgentBatchResultContent(tasks, results),+ undefined,+ { operationId: state.operationId },+ );+// Get latest messages from storeconst updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];const newState = { ...state, messages: updatedMessages };