🤯 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: unify agent runtime executor registry (#17265)
Arvin Xue3d39e51d921
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.tsindex 854db419a46..fff68931755 100644--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts@@ -1,16 +1,5 @@import type { AgentInstruction, InstructionExecutor } from '@lobechat/agent-runtime';-import {- callLlm as createCallLlmExecutor,- callTool as createCallToolExecutor,- callToolsBatch as createCallToolsBatchExecutor,- compressContext as createCompressContextExecutor,- execSubAgent as createExecSubAgentExecutor,- execSubAgents as createExecSubAgentsExecutor,- finish as createFinishExecutor,- requestHumanApprove as createRequestHumanApproveExecutor,- resolveAbortedTools as createResolveAbortedToolsExecutor,- resolveBlockedTools as createResolveBlockedToolsExecutor,-} from '@lobechat/agent-runtime';+import { createAgentRuntimeExecutors } from '@lobechat/agent-runtime';import { buildHost } from './buildHost';import type { RuntimeExecutorContext } from './context';@@ -20,22 +9,5 @@ export { type RuntimeExecutorContext } from './context';export const createRuntimeExecutors = (ctx: RuntimeExecutorContext,): Partial<Record<AgentInstruction['type'], InstructionExecutor>> => {- // Package-hosted executors take an AgentRuntimeHost (transport adapters +- // operation context) instead of the raw server ctx. Built once per operation.- const host = buildHost(ctx);-- return {- call_llm: createCallLlmExecutor(host),- call_tool: createCallToolExecutor(host),- call_tools_batch: createCallToolsBatchExecutor(host),- compress_context: createCompressContextExecutor(host),- 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),- request_human_approve: createRequestHumanApproveExecutor(host),- resolve_aborted_tools: createResolveAbortedToolsExecutor(host),- resolve_blocked_tools: createResolveBlockedToolsExecutor(host),- };+ return createAgentRuntimeExecutors(buildHost(ctx));};diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex cc326c54c95..2fbbbf97012 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -234,6 +234,21 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {};});+ it('registers the same complete package executor matrix as the client', () => {+ expect(Object.keys(createRuntimeExecutors(ctx))).toEqual([+ 'call_llm',+ 'call_tool',+ 'call_tools_batch',+ 'compress_context',+ 'exec_sub_agent',+ 'exec_sub_agents',+ 'finish',+ 'request_human_approve',+ 'resolve_aborted_tools',+ 'resolve_blocked_tools',+ ]);+ });+// Helper to create a valid mock usage objectconst createMockUsage = () => ({humanInteraction: {diff --git a/docs/development/basic/chat-api.mdx b/docs/development/basic/chat-api.mdxindex ec76b81c571..54e79db56db 100644--- a/docs/development/basic/chat-api.mdx+++ b/docs/development/basic/chat-api.mdx@@ -89,7 +89,7 @@ is driven by the `AgentRuntime.step()` loop.3. Create `GeneralChatAgent` (the "brain" that decideswhat to do next) and `AgentRuntime` (the "engine"that executes instructions)-4. Inject custom executors via `createAgentExecutors()`+4. Bind the shared package executors to client transports via `createClientRuntimeExecutors()`**Execution Loop**:diff --git a/docs/development/basic/chat-api.zh-CN.mdx b/docs/development/basic/chat-api.zh-CN.mdxindex 87e71be03e0..a7728ab06bf 100644--- a/docs/development/basic/chat-api.zh-CN.mdx+++ b/docs/development/basic/chat-api.zh-CN.mdx@@ -83,7 +83,7 @@ Agent Runtime 是整个 chat 流程的**核心执行引擎**。2. 通过 `createAgentToolsEngine()` 创建工具注册表3. 创建 `GeneralChatAgent`("大脑",决定下一步做什么)和 `AgentRuntime`("引擎",执行指令)-4. 通过 `createAgentExecutors()` 注入自定义执行器+4. 通过 `createClientRuntimeExecutors()` 将 package 共享执行器绑定到客户端 transport**执行循环**:diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 7a682451afd..fc48a62beeb 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -625,30 +625,6 @@ export class GeneralChatAgent implements Agent {type: 'exec_sub_agents',};}-- // Client-side sub-agent (single, desktop only)- if (stateType === 'execClientSubAgent') {- const { parentMessageId: execParentId, task } = data.state as {- parentMessageId: string;- task: any;- };- return {- payload: { parentMessageId: execParentId, task },- type: 'exec_client_sub_agent',- };- }-- // Client-side sub-agents (multiple, desktop only)- if (stateType === 'execClientSubAgents') {- const { parentMessageId: execParentId, tasks } = data.state as {- parentMessageId: string;- tasks: any[];- };- return {- payload: { parentMessageId: execParentId, tasks },- type: 'exec_client_sub_agents',- };- }}// Scope pending check to the current assistant turn so stalediff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 12afdfd7025..515aed3aadf 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -638,72 +638,6 @@ describe('GeneralChatAgent', () => {});});- it('should return exec_client_sub_agent for single client-side sub-agent (execClientSubAgent)', async () => {- const agent = new GeneralChatAgent({- agentConfig: { maxSteps: 100 },- operationId: 'test-session',- modelRuntimeConfig: mockModelRuntimeConfig,- });-- const state = createMockState();- const context = createMockContext('tool_result', {- parentMessageId: 'tool-msg-1',- stop: true,- data: {- state: {- type: 'execClientSubAgent',- parentMessageId: 'exec-parent-msg',- task: { type: 'localFile', path: '/path/to/file' },- },- },- });-- const result = await agent.runner(context, state);-- expect(result).toEqual({- type: 'exec_client_sub_agent',- payload: {- parentMessageId: 'exec-parent-msg',- task: { type: 'localFile', path: '/path/to/file' },- },- });- });-- it('should return exec_client_sub_agents for multiple client-side sub-agents (execClientSubAgents)', async () => {- const agent = new GeneralChatAgent({- agentConfig: { maxSteps: 100 },- operationId: 'test-session',- modelRuntimeConfig: mockModelRuntimeConfig,- });-- const state = createMockState();- const tasks = [- { type: 'localFile', path: '/path/to/file1' },- { type: 'localFile', path: '/path/to/file2' },- ];- const context = createMockContext('tool_result', {- parentMessageId: 'tool-msg-1',- stop: true,- data: {- state: {- type: 'execClientSubAgents',- parentMessageId: 'exec-parent-msg',- tasks,- },- },- });-- const result = await agent.runner(context, state);-- expect(result).toEqual({- type: 'exec_client_sub_agents',- payload: {- parentMessageId: 'exec-parent-msg',- tasks,- },- });- });-it('should not trigger exec_sub_agent when stop is false', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },diff --git a/packages/agent-runtime/src/executors/index.ts b/packages/agent-runtime/src/executors/index.tsindex cde9a28dc3c..49d18f8a46a 100644--- a/packages/agent-runtime/src/executors/index.ts+++ b/packages/agent-runtime/src/executors/index.ts@@ -3,6 +3,7 @@ export * from './callLlmFinalizer';export * from './compressContext';export * from './finish';export * from './humanApprove';+export * from './registry';export * from './resolveTools';export * from './subAgent';export * from './tool';diff --git a/packages/agent-runtime/src/executors/registry.test.ts b/packages/agent-runtime/src/executors/registry.test.tsnew file mode 100644index 00000000000..251b9fc75e1--- /dev/null+++ b/packages/agent-runtime/src/executors/registry.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it, vi } from 'vitest';++import type { AgentRuntimeHost } from '../transport';+import type { AgentInstruction, AgentState } from '../types';+import { createAgentRuntimeExecutors } from './registry';++const executorTypes = [+ 'call_llm',+ 'call_tool',+ 'call_tools_batch',+ 'compress_context',+ 'exec_sub_agent',+ 'exec_sub_agents',+ 'finish',+ 'request_human_approve',+ 'resolve_aborted_tools',+ 'resolve_blocked_tools',+];++const createState = (stepCount = 0) =>+ ({+ cost: {+ calculatedAt: '2026-07-16T00:00:00.000Z',+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt: '2026-07-16T00:00:00.000Z',+ lastModified: '2026-07-16T00:00:00.000Z',+ messages: [],+ operationId: 'operation-1',+ status: 'running',+ stepCount,+ 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 },+ },+ }) satisfies AgentState;++const createHost = (stepIndex: number, publishEvent = vi.fn()) =>+ ({+ operation: { operationId: 'operation-1', stepIndex },+ transports: {+ messages: {},+ operationStore: { clearRunningMark: vi.fn() },+ stream: { publishError: vi.fn(), publishEvent },+ },+ }) as unknown as AgentRuntimeHost;++describe('createAgentRuntimeExecutors', () => {+ it('registers the complete package-owned instruction matrix', () => {+ const executors = createAgentRuntimeExecutors(createHost(0));++ expect(Object.keys(executors)).toEqual(executorTypes);+ });++ it('resolves a fresh host from the current instruction and state', async () => {+ const publishEvent = vi.fn();+ const resolveHost = vi.fn((_instruction, state: AgentState) =>+ createHost(state.stepCount, publishEvent),+ );+ const executors = createAgentRuntimeExecutors(resolveHost);+ const instruction: Extract<AgentInstruction, { type: 'finish' }> = {+ reason: 'completed',+ type: 'finish',+ };+ const state = createState(7);++ await executors.finish!(instruction, state);++ expect(resolveHost).toHaveBeenCalledWith(instruction, state, undefined);+ expect(publishEvent).toHaveBeenCalledWith(expect.objectContaining({ stepIndex: 7 }));+ });+});diff --git a/packages/agent-runtime/src/executors/registry.ts b/packages/agent-runtime/src/executors/registry.tsnew file mode 100644index 00000000000..97e8680d706--- /dev/null+++ b/packages/agent-runtime/src/executors/registry.ts@@ -0,0 +1,55 @@+import type { AgentRuntimeHost } from '../transport';+import type {+ AgentInstruction,+ AgentRuntimeContext,+ AgentState,+ InstructionExecutor,+} from '../types';+import { callLlm } from './callLlm';+import { compressContext } from './compressContext';+import { finish } from './finish';+import { requestHumanApprove } from './humanApprove';+import { resolveAbortedTools, resolveBlockedTools } from './resolveTools';+import { execSubAgent, execSubAgents } from './subAgent';+import { callTool, callToolsBatch } from './tool';++export type AgentRuntimeHostResolver = (+ instruction: AgentInstruction,+ state: AgentState,+ runtimeContext?: AgentRuntimeContext,+) => AgentRuntimeHost;++type ExecutorFactory = (host: AgentRuntimeHost) => InstructionExecutor;++const executorFactories = {+ call_llm: callLlm,+ call_tool: callTool,+ call_tools_batch: callToolsBatch,+ compress_context: compressContext,+ exec_sub_agent: execSubAgent,+ exec_sub_agents: execSubAgents,+ finish,+ request_human_approve: requestHumanApprove,+ resolve_aborted_tools: resolveAbortedTools,+ resolve_blocked_tools: resolveBlockedTools,+} satisfies Partial<Record<AgentInstruction['type'], ExecutorFactory>>;++/** Bind every package-owned instruction executor to a static or per-step host. */+export const createAgentRuntimeExecutors = (+ hostOrResolver: AgentRuntimeHost | AgentRuntimeHostResolver,+): Partial<Record<AgentInstruction['type'], InstructionExecutor>> => {+ const resolveHost: AgentRuntimeHostResolver =+ typeof hostOrResolver === 'function' ? hostOrResolver : () => hostOrResolver;++ return Object.fromEntries(+ Object.entries(executorFactories).map(([type, factory]) => [+ type,+ (instruction: AgentInstruction, state: AgentState, runtimeContext?: AgentRuntimeContext) =>+ factory(resolveHost(instruction, state, runtimeContext))(+ instruction,+ state,+ runtimeContext,+ ),+ ]),+ );+};diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.tsindex 29d8080fbea..533a25cf8ed 100644--- a/packages/agent-runtime/src/executors/tool.test.ts+++ b/packages/agent-runtime/src/executors/tool.test.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import type { AgentRuntimeHost } from '../transport';-import type { AgentInstruction, AgentState } from '../types';+import type { AgentInstruction, AgentRuntimeContext, AgentState } from '../types';import { callTool, callToolsBatch } from './tool';const createCost = () => ({@@ -238,7 +238,7 @@ describe('tool executors', () => {expect(createToolMessage).not.toHaveBeenCalled();});- it('returns client sub-agent stop states to the agent but terminates other stop results', async () => {+ it('terminates removed client sub-agent stop states like other stop results', async () => {const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },type: 'call_tool',@@ -253,15 +253,6 @@ describe('tool executors', () => {success: true,},});- const delegated = await callTool(host)(instruction, createState());-- expect(delegated.newState.status).toBe('running');- expect(delegated.nextContext?.payload).toMatchObject({ stop: true });-- runTool.mockResolvedValueOnce({- attempts: 1,- result: { content: 'Spoken', state: { type: 'speak' }, stop: true, success: true },- });const stopped = await callTool(host)(instruction, createState());expect(stopped.newState.status).toBe('done');@@ -361,6 +352,35 @@ describe('tool executors', () => {);});+ it('passes the current step context to every tool in a batch', async () => {+ const stepContext = {+ activatedToolIds: ['page-editor'],+ hasQueuedMessages: true,+ };+ const runtimeContext = {+ phase: 'llm_result',+ stepContext,+ } satisfies AgentRuntimeContext;++ await callToolsBatch(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall('tool-a'), createToolCall('tool-b')],+ },+ type: 'call_tools_batch',+ },+ createState(),+ runtimeContext,+ );++ expect(runTool).toHaveBeenCalledTimes(2);+ expect(runTool.mock.calls.map(([, runContext]) => runContext.stepContext)).toEqual([+ stepContext,+ stepContext,+ ]);+ });+it('executes server tools in a mixed batch then parks for client tools', async () => {const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {payload: {diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex 38c122d7df4..5aef9f0b910 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -529,9 +529,7 @@ export const callTool =const legacyAgentInvocationStateType = executionResult.state?.type as string | undefined;const isLegacyAgentInvocationState =legacyAgentInvocationStateType === 'execSubAgent' ||- legacyAgentInvocationStateType === 'execSubAgents' ||- legacyAgentInvocationStateType === 'execClientSubAgent' ||- legacyAgentInvocationStateType === 'execClientSubAgents';+ legacyAgentInvocationStateType === 'execSubAgents';if (executionResult.stop && !isLegacyAgentInvocationState) {newState.status = 'done';@@ -584,7 +582,7 @@ export const callTool =export const callToolsBatch =(host: AgentRuntimeHost): InstructionExecutor =>- async (instruction, state) => {+ async (instruction, state, runtimeContext) => {const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tools_batch' }>;const parentMessageId = payload.parentMessageId as string;const toolsCalling = payload.toolsCalling as ChatToolPayload[];@@ -617,7 +615,14 @@ export const callToolsBatch =await Promise.all(toolsToExecute.map(async (tool) => {- const runContext = createRunContext({ host, mode: 'batch', parentMessageId, state, tool });+ const runContext = createRunContext({+ host,+ mode: 'batch',+ parentMessageId,+ state,+ stepContext: runtimeContext?.stepContext,+ tool,+ });await host.transports.stream.publishEvent({data: { parentMessageId, toolCalling: tool },diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.tsindex cc198e8d594..5e80295b349 100644--- a/packages/agent-runtime/src/types/instruction.ts+++ b/packages/agent-runtime/src/types/instruction.ts@@ -309,26 +309,6 @@ export interface AgentInstructionExecSubAgents extends AgentInstructionBase {type: 'exec_sub_agents';}-export interface AgentInstructionExecClientSubAgent extends AgentInstructionBase {- payload: {- /** Parent message ID (tool message that dispatched the sub-agent) */- parentMessageId: string;- /** Sub-agent to execute */- task: SubAgentTask;- };- type: 'exec_client_sub_agent';-}--export interface AgentInstructionExecClientSubAgents extends AgentInstructionBase {- payload: {- /** Parent message ID (tool message that dispatched the sub-agents) */- parentMessageId: string;- /** Array of sub-agents to execute */- tasks: SubAgentTask[];- };- type: 'exec_client_sub_agents';-}-// ─ Human Interaction ─────────────────────────────────────export interface AgentInstructionRequestHumanPrompt extends AgentInstructionBase {@@ -391,8 +371,6 @@ export type AgentInstruction =// Sub-Agent| AgentInstructionExecSubAgent| AgentInstructionExecSubAgents- | AgentInstructionExecClientSubAgent- | AgentInstructionExecClientSubAgents// Human Interaction| AgentInstructionRequestHumanPrompt| AgentInstructionRequestHumanSelectdiff --git a/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts b/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.tsindex fddc9fb3132..c624026afc5 100644--- a/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts+++ b/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts@@ -173,7 +173,7 @@ describe('createGroupOrchestrationExecutors', () => {const callArgs = (mockStore.executeClientAgent as any).mock.calls[0][0];// The key assertion: isSupervisor must be true- // This is used by createAgentExecutors to set metadata.isSupervisor on assistant messages+ // This is used by the client runtime host to set metadata.isSupervisor on assistant messagesexpect(callArgs.context).toMatchObject({agentId: TEST_IDS.SUPERVISOR_AGENT_ID,isSupervisor: true,diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.tssimilarity index 94%rename from src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.tsindex fe8e5226cdf..ce84be26285 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts@@ -6,7 +6,7 @@ import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_CONFIG } from '@/const/settingimport { chatService } from '@/services/chat';import type { ResolvedAgentConfig } from '@/services/chat/mecha';import { messageService } from '@/services/message';-import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';+import { createClientRuntimeExecutors } from '@/store/chat/agents/transports/createClientRuntimeExecutors';import type { ChatStore } from '@/store/chat/store';const messageKey = 'agent-1_topic-1';@@ -95,7 +95,7 @@ const createInstruction = (overrides: Record<string, unknown> = {}) => ({type: 'call_llm' as const,});-describe('createAgentExecutors call_llm', () => {+describe('createClientRuntimeExecutors call_llm', () => {beforeEach(() => {vi.spyOn(chatService, 'buildAssistantMessageContext').mockImplementation(async ({ messages, model, provider }) => ({@@ -131,12 +131,11 @@ describe('createAgentExecutors call_llm', () => {});return new Response();});- const executor = createAgentExecutors({+ const executor = createClientRuntimeExecutors({agentConfig: createResolvedAgentConfig(),get: () => store,messageKey,operationId,- parentId: userMessage.id,}).call_llm!;const result = await executor(@@ -184,12 +183,11 @@ describe('createAgentExecutors call_llm', () => {await options?.onFinish?.('Answer after compression', { type: 'stop' });return new Response();});- const executor = createAgentExecutors({+ const executor = createClientRuntimeExecutors({agentConfig: createResolvedAgentConfig(),get: () => store,messageKey,operationId,- parentId: compressedAssistant.id,}).call_llm!;const result = await executor(@@ -224,12 +222,11 @@ describe('createAgentExecutors call_llm', () => {await options?.onFinish?.('', { type: 'stop' });return new Response();});- const executor = createAgentExecutors({+ const executor = createClientRuntimeExecutors({agentConfig: createResolvedAgentConfig(),get: () => store,messageKey,operationId,- parentId: userMessage.id,}).call_llm!;const result = await executor(@@ -263,12 +260,11 @@ describe('createAgentExecutors call_llm', () => {await options?.onFinish?.('Regenerated', { type: 'stop' });return new Response();});- const executor = createAgentExecutors({+ const executor = createClientRuntimeExecutors({agentConfig: createResolvedAgentConfig(),get: () => store,messageKey,operationId,- parentId: assistantMessage.id,}).call_llm!;await executor(@@ -294,12 +290,11 @@ describe('createAgentExecutors call_llm', () => {await options?.onFinish?.('Partial', { type: 'abort' });return new Response();});- const executor = createAgentExecutors({+ const executor = createClientRuntimeExecutors({agentConfig: createResolvedAgentConfig(),get: () => store,messageKey,operationId,- parentId: userMessage.id,}).call_llm!;const result = await executor(@@ -323,12 +318,11 @@ describe('createAgentExecutors call_llm', () => {operation.abortController.abort();throw new DOMException('The operation was aborted', 'AbortError');});- const executor = createAgentExecutors({+ const executor = createClientRuntimeExecutors({agentConfig: createResolvedAgentConfig(),get: () => store,messageKey,operationId,- parentId: userMessage.id,}).call_llm!;const result = await executor(diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-task.test.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-task.test.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-tasks.test.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-tasks.test.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/finish.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/finish.test.tssimilarity index 99%rename from src/store/chat/agents/__tests__/createAgentExecutors/finish.test.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/finish.test.tsindex 1fc119a2694..150e8ecdd66 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/finish.test.ts+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/finish.test.ts@@ -268,7 +268,7 @@ describe('finish executor', () => {const context = createTestContext();const instruction = createFinishInstruction('completed');const state = createInitialState({ operationId: 'test', stepCount: 5 });- const originalState = JSON.parse(JSON.stringify(state));+ const originalState = structuredClone(state);// Whenconst result = await executeWithMockContext({diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/index.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/index.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/fixtures/index.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/index.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockInstructions.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockInstructions.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockInstructions.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockInstructions.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockMessages.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockMessages.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockMessages.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockMessages.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockOperations.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockOperations.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockOperations.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockOperations.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockStore.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockStore.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/assertions.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/helpers/assertions.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/helpers/assertions.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/helpers/assertions.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/index.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/helpers/index.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/helpers/index.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/helpers/index.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/operationTestUtils.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/helpers/operationTestUtils.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/helpers/operationTestUtils.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/helpers/operationTestUtils.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/helpers/testExecutor.tssimilarity index 96%rename from src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/helpers/testExecutor.tsindex 3344e8fc05b..a1b51c0a9c1 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.ts+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/helpers/testExecutor.ts@@ -3,7 +3,7 @@ import type { MessageMapScope, MessageMetadata } from '@lobechat/types';import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_CONFIG } from '@/const/settings';import { type ResolvedAgentConfig } from '@/services/chat/mecha';-import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';+import { createClientRuntimeExecutors } from '@/store/chat/agents/transports/createClientRuntimeExecutors';import { type OperationType } from '@/store/chat/slices/operation/types';import { type ChatStore } from '@/store/chat/store';@@ -74,13 +74,12 @@ export const executeWithMockContext = async ({}// Create executors with mock context- const executors = createAgentExecutors({+ const executors = createClientRuntimeExecutors({agentConfig: createMockResolvedAgentConfig(),get: () => mockStore,metadata,messageKey: context.messageKey,operationId: context.operationId,- parentId: context.parentId,});const executorFn = executors[executor];diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.tsdiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/resolve-aborted-tools.test.tssimilarity index 100%rename from src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.tsrename to src/store/chat/agents/__tests__/clientRuntimeExecutors/resolve-aborted-tools.test.tsdiff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.tsdeleted file mode 100644index 0a14a1f5f18..00000000000--- a/src/store/chat/agents/createAgentExecutors.ts+++ /dev/null@@ -1,62 +0,0 @@-import type {- AgentInstruction,- AgentRuntimeHost,- InstructionExecutor,-} from '@lobechat/agent-runtime';-import {- callLlm as createCallLlmExecutor,- callTool as createCallToolExecutor,- compressContext as createCompressContextExecutor,- execSubAgent as createExecSubAgentExecutor,- execSubAgents as createExecSubAgentsExecutor,- finish as createFinishExecutor,- requestHumanApprove as createRequestHumanApproveExecutor,- resolveAbortedTools as createResolveAbortedToolsExecutor,-} from '@lobechat/agent-runtime';-import { type ToolsEngine } from '@lobechat/context-engine';-import { type MessageMetadata } from '@lobechat/types';--import { type ResolvedAgentConfig } from '@/services/chat/mecha';-import { type ChatStore } from '@/store/chat/store';--import { buildClientRuntimeHost } from './transports/buildClientRuntimeHost';--/** Bind package-hosted executors to the current client runtime host. */-export const createAgentExecutors = (context: {- agentConfig: ResolvedAgentConfig;- get: () => ChatStore;- metadata?: Pick<MessageMetadata, 'trigger'>;- messageKey: string;- operationId: string;- parentId: string;- toolsEngine?: ToolsEngine;-}) => {- const usePackageExecutor =- (factory: (host: AgentRuntimeHost) => InstructionExecutor): InstructionExecutor =>- (instruction, state, runtimeContext) =>- factory(- buildClientRuntimeHost({- agentConfig: context.agentConfig,- get: context.get,- metadata: context.metadata,- messageKey: context.messageKey,- operationId: context.operationId,- runtimeContext,- stepIndex: state.stepCount,- toolsEngine: context.toolsEngine,- }),- )(instruction, state, runtimeContext);-- const executors: Partial<Record<AgentInstruction['type'], InstructionExecutor>> = {- call_llm: usePackageExecutor(createCallLlmExecutor),- call_tool: usePackageExecutor(createCallToolExecutor),- compress_context: usePackageExecutor(createCompressContextExecutor),- exec_sub_agent: usePackageExecutor(createExecSubAgentExecutor),- exec_sub_agents: usePackageExecutor(createExecSubAgentsExecutor),- finish: usePackageExecutor(createFinishExecutor),- request_human_approve: usePackageExecutor(createRequestHumanApproveExecutor),- resolve_aborted_tools: usePackageExecutor(createResolveAbortedToolsExecutor),- };-- return executors;-};diff --git a/src/store/chat/agents/transports/createClientRuntimeExecutors.test.ts b/src/store/chat/agents/transports/createClientRuntimeExecutors.test.tsnew file mode 100644index 00000000000..82103c2939c--- /dev/null+++ b/src/store/chat/agents/transports/createClientRuntimeExecutors.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';++import type { ResolvedAgentConfig } from '@/services/chat/mecha';+import type { ChatStore } from '@/store/chat/store';++import { createClientRuntimeExecutors } from './createClientRuntimeExecutors';++const executorTypes = [+ 'call_llm',+ 'call_tool',+ 'call_tools_batch',+ 'compress_context',+ 'exec_sub_agent',+ 'exec_sub_agents',+ 'finish',+ 'request_human_approve',+ 'resolve_aborted_tools',+ 'resolve_blocked_tools',+];++describe('createClientRuntimeExecutors', () => {+ it('uses the complete package registry including batch and blocked tool handling', () => {+ const executors = createClientRuntimeExecutors({+ agentConfig: {} as ResolvedAgentConfig,+ get: () => ({}) as ChatStore,+ messageKey: 'agent-1_topic-1',+ operationId: 'operation-1',+ });++ expect(Object.keys(executors)).toEqual(executorTypes);+ });+});diff --git a/src/store/chat/agents/transports/createClientRuntimeExecutors.ts b/src/store/chat/agents/transports/createClientRuntimeExecutors.tsnew file mode 100644index 00000000000..37c7c35845e--- /dev/null+++ b/src/store/chat/agents/transports/createClientRuntimeExecutors.ts@@ -0,0 +1,30 @@+import { createAgentRuntimeExecutors } from '@lobechat/agent-runtime';+import type { ToolsEngine } from '@lobechat/context-engine';+import type { MessageMetadata } from '@lobechat/types';++import type { ResolvedAgentConfig } from '@/services/chat/mecha';+import type { ChatStore } from '@/store/chat/store';++import { buildClientRuntimeHost } from './buildClientRuntimeHost';++/** Resolve a fresh client host for each runtime step, then use the shared package registry. */+export const createClientRuntimeExecutors = (context: {+ agentConfig: ResolvedAgentConfig;+ get: () => ChatStore;+ metadata?: Pick<MessageMetadata, 'trigger'>;+ messageKey: string;+ operationId: string;+ toolsEngine?: ToolsEngine;+}) =>+ createAgentRuntimeExecutors((_instruction, state, runtimeContext) =>+ buildClientRuntimeHost({+ agentConfig: context.agentConfig,+ get: context.get,+ metadata: context.metadata,+ messageKey: context.messageKey,+ operationId: context.operationId,+ runtimeContext,+ stepIndex: state.stepCount,+ toolsEngine: context.toolsEngine,+ }),+ );diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 4a4616e91aa..581faed7895 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -38,7 +38,7 @@ import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { aiModelSelectors } from '@/store/aiInfra/selectors';import { getAiInfraStoreState } from '@/store/aiInfra/store';-import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';+import { createClientRuntimeExecutors } from '@/store/chat/agents/transports/createClientRuntimeExecutors';import { topicSelectors } from '@/store/chat/selectors';import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';import {@@ -652,13 +652,12 @@ export class StreamingExecutorActionImpl {});const runtime = new AgentRuntime(agent, {- executors: createAgentExecutors({+ executors: createClientRuntimeExecutors({agentConfig, // Pass pre-resolved config to callLLM executorget: this.#get,metadata: params.metadata,messageKey,operationId,- parentId: params.parentMessageId,toolsEngine, // Pass toolsEngine for dynamic tool injection via activateTools}),getOperation: (opId: string) => {diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex c7ae4eac931..30b4555ad26 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -60,7 +60,6 @@ export type OperationType =// === Sub-Agent (Desktop only) ===| 'execClientSubAgent' // Dispatch single sub-agent on the desktop client- | 'execClientSubAgents' // Dispatch multiple sub-agents on the desktop client// === Context Compression ===// Context compression (compress old messages into summary)