Skip to content

🀯 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.

♻️ refactor: move tool executors into agent-runtime (#16914)

Arvin Xue2f68639ab54
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
index 5b59f2aa2ec..85b6ee20fb9 100644
--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
@@ -1,17 +1,16 @@
+import type { AgentInstruction, InstructionExecutor } from '@lobechat/agent-runtime';
import {
- type AgentInstruction,
+ callTool as createCallToolExecutor,
+ callToolsBatch as createCallToolsBatchExecutor,
finish as createFinishExecutor,
- type InstructionExecutor,
requestHumanApprove as createRequestHumanApproveExecutor,
resolveAbortedTools as createResolveAbortedToolsExecutor,
resolveBlockedTools as createResolveBlockedToolsExecutor,
} from '@lobechat/agent-runtime';
import { buildHost } from './buildHost';
-import { type RuntimeExecutorContext } from './context';
+import type { RuntimeExecutorContext } from './context';
import { callLlm } from './executors/callLlm';
-import { callTool } from './executors/callTool';
-import { callToolsBatch } from './executors/callToolsBatch';
import { compressContext } from './executors/compressContext';
import { execSubAgent, execSubAgents } from './executors/execSubAgent';
@@ -26,8 +25,8 @@ export const createRuntimeExecutors = (
return {
call_llm: callLlm(ctx),
- call_tool: callTool(ctx),
- call_tools_batch: callToolsBatch(ctx),
+ call_tool: createCallToolExecutor(host),
+ call_tools_batch: createCallToolsBatchExecutor(host),
compress_context: compressContext(ctx),
exec_sub_agent: execSubAgent(ctx),
exec_sub_agents: execSubAgents(ctx),
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 6bdb643c905..2dd1d344d47 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -134,7 +134,7 @@ vi.mock('@/server/services/file', () => ({
})),
}));
-describe('RuntimeExecutors', () => {
+describe('RuntimeExecutors', { timeout: 60_000 }, () => {
let mockMessageModel: any;
let mockStreamManager: any;
let mockToolExecutionService: any;
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
index 5d2cc7f5453..4b539b1fb4e 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
@@ -1,9 +1,11 @@
import type {
MessageTransport,
QueryMessagesInput,
+ QueryMessagesOptions,
RuntimeMessageRef,
UpdateToolMessageInput,
} from '@lobechat/agent-runtime';
+import { parse } from '@lobechat/conversation-flow';
import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@lobechat/types';
import { type MessageModel } from '@/database/models/message';
@@ -17,7 +19,15 @@ import {
* Server {@link MessageTransport} adapter β€” delegates to `MessageModel` (DB).
*/
export class ServerMessageTransport implements MessageTransport {
- constructor(private readonly messageModel: MessageModel) {}
+ constructor(
+ private readonly messageModel: MessageModel,
+ private readonly options: {
+ postProcessUrl?: (
+ path: string | null,
+ file: { fileType: string; id?: string | null },
+ ) => Promise<string>;
+ } = {},
+ ) {}
createAssistantMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {
return this.messageModel.create(params);
@@ -43,8 +53,18 @@ export class ServerMessageTransport implements MessageTransport {
return message ? { id: message.id } : undefined;
}
- query(params?: QueryMessagesInput): Promise<UIChatMessage[]> {
- return this.messageModel.query(params);
+ async query(
+ params?: QueryMessagesInput,
+ options?: QueryMessagesOptions,
+ ): Promise<UIChatMessage[]> {
+ const messages = await this.messageModel.query(params, {
+ postProcessUrl: options?.resolveAssetUrls ? this.options.postProcessUrl : undefined,
+ });
+
+ if (!options?.flatten) return messages;
+
+ const { flatList } = parse(messages);
+ return flatList;
}
async update(id: string, params: Partial<UpdateMessageParams>): Promise<void> {
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
new file mode 100644
index 00000000000..5e5602000e7
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -0,0 +1,342 @@
+import type { ToolRunContext, ToolRunExecution, ToolTransport } from '@lobechat/agent-runtime';
+import { executeToolWithRetry } from '@lobechat/agent-runtime';
+import { SpanStatusCode } from '@lobechat/observability-otel/api';
+import {
+ buildExecuteToolAttributes,
+ buildExecuteToolResultAttributes,
+ executeToolSpanName,
+ tracer as agentRuntimeTracer,
+} from '@lobechat/observability-otel/modules/agent-runtime';
+import type { ChatToolPayload } from '@lobechat/types';
+
+import { AgentModel } from '@/database/models/agent';
+import { isDeviceCapablePlan } from '@/helpers/executionTarget';
+import type { DeviceAccessReason } from '@/server/services/aiAgent/deviceToolAudit';
+import {
+ isDeviceToolIdentifier,
+ logDeviceToolAudit,
+} from '@/server/services/aiAgent/deviceToolAudit';
+
+import type { RuntimeExecutorContext } from '../context';
+import { dispatchClientTool } from '../dispatchClientTool';
+import {
+ archiveRuntimeToolResult,
+ buildServerAgentMemberRunner,
+ buildServerVirtualSubAgentRunner,
+ GEN_AI_FUNCTION_TOOL_TYPE,
+ isOperationInterrupted,
+ log,
+ TOOL_MAX_RETRIES,
+ TOOL_PRICING,
+} from '../executorHelpers';
+import { resolveRunActiveDeviceId } from '../executors/resolveRunActiveDeviceId';
+import { resolveRunProjectSkills } from '../executors/resolveRunProjectSkills';
+import { resolveToolTimeoutMs } from '../resolveToolTimeout';
+
+export class ServerToolTransport implements ToolTransport {
+ maxRetries = TOOL_MAX_RETRIES;
+
+ constructor(private readonly ctx: RuntimeExecutorContext) {}
+
+ getCost(toolName: string) {
+ return TOOL_PRICING[toolName] || 0;
+ }
+
+ async handleError(
+ chatToolPayload: ChatToolPayload,
+ error: unknown,
+ context: ToolRunContext,
+ ): Promise<void> {
+ const { hookDispatcher, operationId, stepIndex, userId } = this.ctx;
+
+ if (hookDispatcher) {
+ hookDispatcher
+ .dispatch(
+ operationId,
+ 'onToolCallError',
+ {
+ apiName: chatToolPayload.apiName,
+ args: context.parsedArgs,
+ callIndex: context.callIndex,
+ error: error instanceof Error ? error.message : String(error),
+ identifier: chatToolPayload.identifier,
+ operationId,
+ stepIndex,
+ userId,
+ },
+ context.state.metadata?._hooks,
+ )
+ .catch(() => {});
+ }
+
+ console.error(
+ `[StreamingToolExecutor] Tool execution failed for operation ${operationId}:${stepIndex}:`,
+ error,
+ );
+ }
+
+ async run(chatToolPayload: ChatToolPayload, context: ToolRunContext): Promise<ToolRunExecution> {
+ const { operationId, serverDB, stepIndex, streamManager, toolExecutionService, userId } =
+ this.ctx;
+ const operationLogId = `${operationId}:${stepIndex}`;
+ const executeToolSpan = agentRuntimeTracer.startSpan(executeToolSpanName(context.toolName), {
+ attributes: buildExecuteToolAttributes({
+ operationId,
+ stepIndex,
+ toolCallId: chatToolPayload.id,
+ toolName: context.toolName,
+ toolSource: context.toolSource,
+ toolType: GEN_AI_FUNCTION_TOOL_TYPE,
+ }),
+ });
+
+ try {
+ const hookResult = await this.dispatchBeforeToolCall(chatToolPayload, context);
+ let toolCallMocked = false;
+
+ if (isDeviceToolIdentifier(chatToolPayload.identifier) && !hookResult?.isMocked) {
+ const policy = context.state.metadata?.deviceAccessPolicy as
+ { canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
+ logDeviceToolAudit({
+ apiName: chatToolPayload.apiName,
+ botContext: context.state.metadata?.botContext,
+ canUseDevice: policy?.canUseDevice ?? true,
+ messageId: context.state.metadata?.sourceMessageId,
+ operationId,
+ reason: policy?.reason ?? 'first-party',
+ toolIdentifier: chatToolPayload.identifier,
+ topicId: this.ctx.topicId,
+ userId,
+ });
+ }
+
+ let execution: ToolRunExecution;
+ if (hookResult?.isMocked) {
+ log(`[${operationLogId}] Tool ${context.toolName} mocked by beforeToolCall hook`);
+ toolCallMocked = true;
+ execution = {
+ attempts: 0,
+ mocked: true,
+ result: { content: hookResult.content, executionTime: 0, success: true },
+ };
+ } else if (
+ chatToolPayload.executor === 'client' &&
+ typeof streamManager.sendToolExecute === 'function'
+ ) {
+ log(`[${operationLogId}] Dispatching tool ${context.toolName} to client via Agent Gateway`);
+ const timeoutMs = resolveToolTimeoutMs({
+ apiName: chatToolPayload.apiName,
+ args: context.parsedArgs,
+ manifest: context.effectiveManifestMap[chatToolPayload.identifier],
+ });
+ const dispatchResult = await dispatchClientTool(chatToolPayload, {
+ operationId,
+ streamManager,
+ timeoutMs,
+ });
+ execution = { attempts: 1, result: dispatchResult };
+ } else {
+ if (context.toolSource && !chatToolPayload.source) {
+ chatToolPayload.source = context.toolSource as any;
+ }
+
+ const timeoutMs = resolveToolTimeoutMs({
+ apiName: chatToolPayload.apiName,
+ args: context.parsedArgs,
+ manifest: context.effectiveManifestMap[chatToolPayload.identifier],
+ });
+ const agentVisibility = await this.resolveAgentVisibility(context);
+
+ log(`[${operationLogId}] Executing tool ${context.toolName} ...`);
+ execution = await executeToolWithRetry(
+ () =>
+ toolExecutionService.executeTool(chatToolPayload, {
+ activatedSkills: context.activatedSkills as any,
+ activeDeviceId: resolveRunActiveDeviceId(context.state.metadata),
+ agentId: context.state.metadata?.agentId,
+ agentMember: buildServerAgentMemberRunner(
+ this.ctx,
+ context.state,
+ chatToolPayload,
+ context.parentMessageId,
+ ),
+ ...(agentVisibility !== undefined && { agentVisibility }),
+ assistantMessageId: context.parentMessageId,
+ deviceCapable: context.state.metadata?.executionPlan
+ ? isDeviceCapablePlan(context.state.metadata.executionPlan)
+ : undefined,
+ documentId: context.state.metadata?.documentId,
+ editingAgentId: context.state.metadata?.editingAgentId,
+ execSubAgent: this.ctx.execSubAgent,
+ executionTimeoutMs: timeoutMs,
+ groupId: context.state.metadata?.groupId,
+ isSubAgent: context.state.metadata?.isSubAgent === true,
+ memoryToolPermission:
+ context.state.metadata?.agentConfig?.chatConfig?.memory?.toolPermission,
+ messageId: context.state.metadata?.sourceMessageId,
+ operationId,
+ projectSkills: resolveRunProjectSkills(context.state.metadata),
+ scope: context.state.metadata?.scope,
+ serverDB,
+ skipResultTruncation: true,
+ subAgent: buildServerVirtualSubAgentRunner(
+ this.ctx,
+ context.state,
+ chatToolPayload,
+ context.parentMessageId,
+ ),
+ taskId: context.state.metadata?.taskId,
+ threadId: context.state.metadata?.threadId,
+ toolCallId: chatToolPayload.id,
+ toolManifestMap: context.effectiveManifestMap,
+ toolResultMaxLength: context.toolResultMaxLength,
+ topicId: this.ctx.topicId,
+ userId,
+ workingDirectory: context.state.metadata?.deviceSystemInfo?.workingDirectory,
+ workspaceId: context.state.metadata?.workspaceId ?? this.ctx.workspaceId,
+ }),
+ {
+ isInterrupted: () => isOperationInterrupted(this.ctx),
+ maxRetries: TOOL_MAX_RETRIES,
+ onRetry: ({ attempt, kind, maxAttempts }) =>
+ log(
+ '[%s] Tool %s failed with kind=%s (attempt %d/%d), retrying ...',
+ operationLogId,
+ context.toolName,
+ kind,
+ attempt,
+ maxAttempts,
+ ),
+ },
+ );
+ }
+
+ if (execution.result.deferred) {
+ executeToolSpan.setAttributes(
+ buildExecuteToolResultAttributes({ attempts: execution.attempts, success: true }),
+ );
+ return { ...execution, mocked: toolCallMocked || execution.mocked };
+ }
+
+ const resultWithExecutionTime = {
+ ...execution.result,
+ executionTime: execution.result.executionTime ?? 0,
+ };
+ const executionResult = await archiveRuntimeToolResult(resultWithExecutionTime, {
+ agentId: context.state.metadata?.agentId,
+ identifier: chatToolPayload.identifier,
+ limit: context.toolResultMaxLength,
+ serverDB,
+ toolCallId: chatToolPayload.id,
+ topicId: this.ctx.topicId ?? context.state.metadata?.topicId,
+ userId,
+ workspaceId: context.state.metadata?.workspaceId ?? this.ctx.workspaceId,
+ });
+
+ await this.dispatchAfterToolCall(chatToolPayload, context, executionResult, toolCallMocked);
+
+ executeToolSpan.setAttributes(
+ buildExecuteToolResultAttributes({
+ attempts: execution.attempts,
+ success: executionResult.success,
+ }),
+ );
+
+ return {
+ ...execution,
+ mocked: toolCallMocked || execution.mocked,
+ result: executionResult,
+ };
+ } catch (error) {
+ executeToolSpan.recordException(error as Error);
+ executeToolSpan.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ executeToolSpan.setAttributes(buildExecuteToolResultAttributes({ success: false }));
+ throw error;
+ } finally {
+ executeToolSpan.end();
+ }
+ }
+
+ private async dispatchBeforeToolCall(chatToolPayload: ChatToolPayload, context: ToolRunContext) {
+ const { hookDispatcher, operationId, stepIndex, userId } = this.ctx;
+ if (!hookDispatcher) return null;
+
+ hookDispatcher
+ .dispatch(
+ operationId,
+ 'beforeToolCall',
+ {
+ apiName: chatToolPayload.apiName,
+ args: context.parsedArgs,
+ callIndex: context.callIndex,
+ identifier: chatToolPayload.identifier,
+ operationId,
+ stepIndex,
+ userId,
+ },
+ context.state.metadata?._hooks,
+ )
+ .catch(() => {});
+
+ return hookDispatcher.dispatchBeforeToolCall(operationId, {
+ apiName: chatToolPayload.apiName,
+ args: context.parsedArgs,
+ callIndex: context.callIndex,
+ identifier: chatToolPayload.identifier,
+ stepIndex,
+ });
+ }
+
+ private async dispatchAfterToolCall(
+ chatToolPayload: ChatToolPayload,
+ context: ToolRunContext,
+ result: ToolRunExecution['result'],
+ mocked: boolean,
+ ) {
+ const { hookDispatcher, operationId, stepIndex, userId } = this.ctx;
+ if (!hookDispatcher) return;
+
+ hookDispatcher
+ .dispatch(
+ operationId,
+ 'afterToolCall',
+ {
+ apiName: chatToolPayload.apiName,
+ args: context.parsedArgs,
+ callIndex: context.callIndex,
+ content: result.content,
+ executionTimeMs: result.executionTime ?? 0,
+ identifier: chatToolPayload.identifier,
+ mocked,
+ operationId,
+ stepIndex,
+ success: result.success,
+ userId,
+ },
+ context.state.metadata?._hooks,
+ )
+ .catch(() => {});
+ }
+
+ private async resolveAgentVisibility(context: ToolRunContext) {
+ if (context.mode !== 'single') return undefined;
+
+ const agentId = context.state.metadata?.agentId;
+ const workspaceId = context.state.metadata?.workspaceId ?? this.ctx.workspaceId;
+ if (!agentId || !this.ctx.serverDB || !this.ctx.userId) return null;
+
+ try {
+ const agentModel = new AgentModel(this.ctx.serverDB, this.ctx.userId, workspaceId);
+ return await agentModel.getAgentVisibility(agentId);
+ } catch (error) {
+ log(
+ `[${this.ctx.operationId}:${this.ctx.stepIndex}] Failed to resolve agent visibility: %O`,
+ error,
+ );
+ return null;
+ }
+ }
+}
diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.ts
index 583da756f98..b0342d2daeb 100644
--- a/apps/server/src/modules/AgentRuntime/buildHost.ts
+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts
@@ -4,7 +4,9 @@ import { ServerLifecycleSink } from './adapters/ServerLifecycleSink';
import { ServerMessageTransport } from './adapters/ServerMessageTransport';
import { ServerOperationStore } from './adapters/ServerOperationStore';
import { ServerStreamSink } from './adapters/ServerStreamSink';
-import { type RuntimeExecutorContext } from './context';
+import { ServerToolTransport } from './adapters/ServerToolTransport';
+import type { RuntimeExecutorContext } from './context';
+import { buildPostProcessUrl } from './executorHelpers';
/**
* Build the {@link AgentRuntimeHost} from the server's `RuntimeExecutorContext`:
@@ -31,7 +33,9 @@ export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => ({
workspaceId: ctx.workspaceId,
},
transports: {
- messages: new ServerMessageTransport(ctx.messageModel),
+ messages: new ServerMessageTransport(ctx.messageModel, {
+ postProcessUrl: buildPostProcessUrl(ctx),
+ }),
operationStore: new ServerOperationStore(
ctx.serverDB,
ctx.userId,
@@ -39,5 +43,6 @@ export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => ({
ctx.topicId,
),
stream: new ServerStreamSink(ctx.streamManager, ctx.operationId),
+ tools: new ServerToolTransport(ctx),
},
});
diff --git a/apps/server/src/modules/AgentRuntime/executors/callTool.ts b/apps/server/src/modules/AgentRuntime/executors/callTool.ts
deleted file mode 100644
index 47a7ec4043f..00000000000
--- a/apps/server/src/modules/AgentRuntime/executors/callTool.ts
+++ /dev/null
@@ -1,660 +0,0 @@
-import {
- type AgentEvent,
- type AgentInstruction,
- executeToolWithRetry,
- extractActivatedSkillsFromMessages,
- type InstructionExecutor,
- UsageCounter,
-} from '@lobechat/agent-runtime';
-import { SpanStatusCode } from '@lobechat/observability-otel/api';
-import {
- buildExecuteToolAttributes,
- buildExecuteToolResultAttributes,
- executeToolSpanName,
- tracer as agentRuntimeTracer,
-} from '@lobechat/observability-otel/modules/agent-runtime';
-import { type ChatToolPayload } from '@lobechat/types';
-
-import { AgentModel } from '@/database/models/agent';
-import { isDeviceCapablePlan } from '@/helpers/executionTarget';
-import {
- type DeviceAccessReason,
- isDeviceToolIdentifier,
- logDeviceToolAudit,
-} from '@/server/services/aiAgent/deviceToolAudit';
-import { type ToolExecutionResultResponse } from '@/server/services/toolExecution';
-
-import { type RuntimeExecutorContext } from '../context';
-import { dispatchClientTool } from '../dispatchClientTool';
-import {
- archiveRuntimeToolResult,
- buildServerAgentMemberRunner,
- buildServerVirtualSubAgentRunner,
- GEN_AI_FUNCTION_TOOL_TYPE,
- isOperationInterrupted,
- log,
- TOOL_MAX_RETRIES,
- TOOL_PRICING,
-} from '../executorHelpers';
-import { formatErrorEventData } from '../formatErrorEventData';
-import {
- createConversationParentMissingError,
- isMidOperationReferenceMissingError,
- isPersistFatal,
- markPersistFatal,
-} from '../messagePersistErrors';
-import { resolveToolTimeoutMs } from '../resolveToolTimeout';
-import { resolveRunActiveDeviceId } from './resolveRunActiveDeviceId';
-import { resolveRunProjectSkills } from './resolveRunProjectSkills';
-
-export const callTool =
- (ctx: RuntimeExecutorContext): InstructionExecutor =>
- async (instruction, state) => {
- const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tool' }>;
- const { operationId, stepIndex, streamManager, toolExecutionService } = ctx;
- const events: AgentEvent[] = [];
-
- const operationLogId = `${operationId}:${stepIndex}`;
- log(`[${operationLogId}] payload: %O`, payload);
-
- // Publish tool execution start event
- await streamManager.publishStreamEvent(operationId, {
- data: payload,
- stepIndex,
- type: 'tool_start',
- });
-
- // payload is { parentMessageId, toolCalling: ChatToolPayload }
- const chatToolPayload: ChatToolPayload = payload.toolCalling;
-
- const toolName = `${chatToolPayload.identifier}/${chatToolPayload.apiName}`;
- const existingToolStats = state.usage?.tools?.byTool?.find((t) => t.name === toolName);
- const callIndex = (existingToolStats?.calls ?? 0) + 1;
-
- let parsedArgs: Record<string, any> = {};
- try {
- parsedArgs =
- typeof chatToolPayload.arguments === 'string'
- ? JSON.parse(chatToolPayload.arguments)
- : (chatToolPayload.arguments ?? {});
- } catch {
- // Keep malformed tool arguments as an empty preview payload; execution still uses raw args.
- }
-
- // OTel execute_tool span. Created up-front so it survives every exit path
- // (client-tool pause / success / error), ended in finally.
- const toolSource =
- state.operationToolSet?.sourceMap?.[chatToolPayload.identifier] ??
- state.toolSourceMap?.[chatToolPayload.identifier];
- const executeToolSpan = agentRuntimeTracer.startSpan(executeToolSpanName(toolName), {
- attributes: buildExecuteToolAttributes({
- operationId,
- stepIndex,
- toolCallId: chatToolPayload.id,
- toolName,
- toolSource,
- toolType: GEN_AI_FUNCTION_TOOL_TYPE,
- }),
- });
-
- try {
- try {
- if (toolSource === 'client') {
- log(`[${operationLogId}] Client function tool detected: ${toolName}, pausing for client`);
-
- // Publish tool call info so streaming can emit function_call events
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'tools_calling',
- toolsCalling: [chatToolPayload] as any,
- });
-
- const newState = structuredClone(state);
- newState.lastModified = new Date().toISOString();
- newState.status = 'waiting_for_async_tool';
- newState.interruption = {
- canResume: true,
- interruptedAt: new Date().toISOString(),
- interruptedInstruction: instruction,
- reason: 'client_tool_execution',
- };
- newState.pendingToolsCalling = [chatToolPayload];
-
- return {
- events: [
- {
- canResume: true,
- interruptedAt: new Date().toISOString(),
- reason: 'client_tool_execution',
- type: 'interrupted',
- },
- ],
- newState,
- // No nextContext β€” loop stops, waiting for client to provide tool result
- };
- }
-
- // Extract toolResultMaxLength from agent config
- const agentConfig = state.metadata?.agentConfig;
- const toolResultMaxLength = agentConfig?.chatConfig?.toolResultMaxLength;
-
- // Build effective manifest map (operation + step-level activations)
- const effectiveManifestMap = {
- ...(state.operationToolSet?.manifestMap ?? state.toolManifestMap),
- ...Object.fromEntries(
- (state.activatedStepTools ?? [])
- .filter((a) => a.manifest)
- .map((a) => [a.id, a.manifest!]),
- ),
- };
-
- // Route to client via Agent Gateway WS when the tool is marked
- // executor='client' and the current stream manager can reach a gateway.
- // Falls through to the normal server path if either is unavailable.
- const canDispatchToClient =
- chatToolPayload.executor === 'client' &&
- typeof streamManager.sendToolExecute === 'function';
-
- let toolCallMocked = false;
- const hookResult = ctx.hookDispatcher
- ? await (async () => {
- // 1. dispatch for observation (webhook in production, local handler logging)
- ctx
- .hookDispatcher!.dispatch(
- operationId,
- 'beforeToolCall',
- {
- apiName: chatToolPayload.apiName,
- args: parsedArgs,
- callIndex,
- identifier: chatToolPayload.identifier,
- operationId,
- stepIndex,
- userId: ctx.userId,
- },
- state.metadata?._hooks,
- )
- .catch(() => {});
- // 2. dispatchBeforeToolCall for mock support (local-only)
- return ctx.hookDispatcher!.dispatchBeforeToolCall(operationId, {
- apiName: chatToolPayload.apiName,
- args: parsedArgs,
- callIndex,
- identifier: chatToolPayload.identifier,
- stepIndex,
- });
- })()
- : null;
-
- let execution: { result: ToolExecutionResultResponse; attempts: number };
- if (isDeviceToolIdentifier(chatToolPayload.identifier) && !hookResult?.isMocked) {
- // Per-call audit for device tools (local-system / remote-device).
- // Emitted before dispatch so the record exists even if dispatch
- // throws. We rely on the engine's enable gate to keep `canUseDevice`
- // true here; recording the policy reason inline lets an operator
- // distinguish first-party vs bot-owner runs without joining logs.
- const policy = state.metadata?.deviceAccessPolicy as
- { canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
- logDeviceToolAudit({
- apiName: chatToolPayload.apiName,
- botContext: state.metadata?.botContext,
- canUseDevice: policy?.canUseDevice ?? true,
- messageId: state.metadata?.sourceMessageId,
- operationId,
- reason: policy?.reason ?? 'first-party',
- toolIdentifier: chatToolPayload.identifier,
- topicId: ctx.topicId,
- userId: ctx.userId,
- });
- }
-
- if (hookResult?.isMocked) {
- log(`[${operationLogId}] Tool ${toolName} mocked by beforeToolCall hook`);
- toolCallMocked = true;
- execution = {
- attempts: 0,
- result: { content: hookResult.content, executionTime: 0, success: true },
- };
- } else if (canDispatchToClient) {
- log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);
- const timeoutMs = resolveToolTimeoutMs({
- apiName: chatToolPayload.apiName,
- args: parsedArgs,
- manifest: effectiveManifestMap[chatToolPayload.identifier],
- });
- const dispatchResult = await dispatchClientTool(chatToolPayload, {
- operationId,
- streamManager,
- timeoutMs,
- });
- execution = { attempts: 1, result: dispatchResult };
- } else {
- // Inject source from sourceMap so BuiltinToolsExecutor can route
- // lobehubSkill / composio tools correctly (LLM responses don't carry source)
- if (toolSource && !chatToolPayload.source) {
- chatToolPayload.source = toolSource;
- }
-
- const timeoutMs = resolveToolTimeoutMs({
- apiName: chatToolPayload.apiName,
- args: parsedArgs,
- manifest: effectiveManifestMap[chatToolPayload.identifier],
- });
- // Resolve caller-agent visibility once so tool runtimes can inherit
- // it onto side-effects (private-agent output β†’ private docs) and gate
- // reads (public agent must not touch caller's private docs). Mirrors
- // the task side's `assertAgentVisibilityCompat` invariant.
- const toolCallAgentId = state.metadata?.agentId;
- const toolCallWorkspaceId = state.metadata?.workspaceId ?? ctx.workspaceId;
- let agentVisibility: 'private' | 'public' | null = null;
- if (toolCallAgentId && ctx.serverDB && ctx.userId) {
- try {
- const agentModel = new AgentModel(ctx.serverDB, ctx.userId, toolCallWorkspaceId);
- agentVisibility = await agentModel.getAgentVisibility(toolCallAgentId);
- } catch (error) {
- // Non-fatal: if we can't resolve visibility, fall back to null so
- // downstream defaults kick in (existing schema fallback for
- // writes; unchanged ownership for reads).
- log(`[${operationLogId}] Failed to resolve agent visibility: %O`, error);
- }
- }
-
- // Execute tool using ToolExecutionService
- log(`[${operationLogId}] Executing tool ${toolName} ...`);
- execution = await executeToolWithRetry(
- () =>
- toolExecutionService.executeTool(chatToolPayload, {
- // Server-side equivalent of the client transport's
- // computeStepContext: state.messages carries the DB rows
- // (pluginState included), so skills execScript can resolve the
- // activated skill archives. Without this the device/sandbox
- // skill preparation silently runs with zero skills.
- activatedSkills: extractActivatedSkillsFromMessages(state.messages),
- // Plan/policy-filtered: a preset or stale metadata id must not route
- // tool execution (e.g. skills execScript) onto a device the resolved
- // plan didn't authorize.
- activeDeviceId: resolveRunActiveDeviceId(state.metadata),
- agentId: toolCallAgentId,
- agentMember: buildServerAgentMemberRunner(
- ctx,
- state,
- chatToolPayload,
- payload.parentMessageId,
- ),
- agentVisibility,
- // Assistant message owning this tool call (β‰  source user message).
- assistantMessageId: payload.parentMessageId,
- deviceCapable: state.metadata?.executionPlan
- ? isDeviceCapablePlan(state.metadata.executionPlan)
- : undefined,
- documentId: state.metadata?.documentId,
- editingAgentId: state.metadata?.editingAgentId,
- execSubAgent: ctx.execSubAgent,
- executionTimeoutMs: timeoutMs,
- groupId: state.metadata?.groupId,
- isSubAgent: state.metadata?.isSubAgent === true,
- memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,
- messageId: state.metadata?.sourceMessageId,
- operationId,
- projectSkills: resolveRunProjectSkills(state.metadata),
- scope: state.metadata?.scope,
- serverDB: ctx.serverDB,
- skipResultTruncation: true,
- subAgent: buildServerVirtualSubAgentRunner(
- ctx,
- state,
- chatToolPayload,
- payload.parentMessageId,
- ),
- taskId: state.metadata?.taskId,
- threadId: state.metadata?.threadId,
- toolCallId: chatToolPayload.id,
- toolManifestMap: effectiveManifestMap,
- toolResultMaxLength,
- topicId: ctx.topicId,
- userId: ctx.userId,
- // Device-bound cwd folded into deviceSystemInfo at operation
- // creation; resume-safe via computeDeviceContext (recovers it
- // from the prior tool message's pluginState.metadata).
- workingDirectory: state.metadata?.deviceSystemInfo?.workingDirectory,
- workspaceId: toolCallWorkspaceId,
- }),
- {
- isInterrupted: () => isOperationInterrupted(ctx),
- maxRetries: TOOL_MAX_RETRIES,
- onRetry: ({ attempt, kind, maxAttempts }) =>
- log(
- '[%s] Tool %s failed with kind=%s (attempt %d/%d), retrying ...',
- operationLogId,
- toolName,
- kind,
- attempt,
- maxAttempts,
- ),
- },
- );
- }
-
- // Deferred tool (e.g. async sub-agent): the executor performed its
- // side-effect and created a pending placeholder; the real result is
- // delivered out-of-band later by a completion bridge. Park like a
- // client tool β€” surface the pending call, hold it in pendingToolsCalling,
- // and do not write a tool_result now.
- if (execution.result.deferred) {
- log(`[${operationLogId}] Tool ${toolName} deferred; parking for async result`);
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'tools_calling',
- toolsCalling: [chatToolPayload] as any,
- });
- executeToolSpan.setAttributes(
- buildExecuteToolResultAttributes({ attempts: execution.attempts, success: true }),
- );
- const newState = structuredClone(state);
- newState.lastModified = new Date().toISOString();
- newState.status = 'waiting_for_async_tool';
- newState.interruption = {
- canResume: true,
- interruptedAt: new Date().toISOString(),
- reason: 'async_tool',
- };
- newState.pendingToolsCalling = [chatToolPayload];
- return {
- events: [
- {
- canResume: true,
- interruptedAt: new Date().toISOString(),
- reason: 'async_tool',
- type: 'interrupted',
- },
- ],
- newState,
- };
- }
-
- const executionResult = await archiveRuntimeToolResult(execution.result, {
- agentId: state.metadata?.agentId,
- identifier: chatToolPayload.identifier,
- limit: toolResultMaxLength,
- serverDB: ctx.serverDB,
- toolCallId: chatToolPayload.id,
- topicId: ctx.topicId ?? state.metadata?.topicId,
- userId: ctx.userId,
- workspaceId: state.metadata?.workspaceId ?? ctx.workspaceId,
- });
- const executionTime = executionResult.executionTime;
- const isSuccess = executionResult.success;
- if (ctx.hookDispatcher) {
- ctx.hookDispatcher
- .dispatch(
- operationId,
- 'afterToolCall',
- {
- apiName: chatToolPayload.apiName,
- args: parsedArgs,
- callIndex,
- content: executionResult.content,
- executionTimeMs: executionTime,
- identifier: chatToolPayload.identifier,
- mocked: toolCallMocked,
- operationId,
- stepIndex,
- success: isSuccess,
- userId: ctx.userId,
- },
- state.metadata?._hooks,
- )
- .catch(() => {});
- }
- log(
- `[${operationLogId}] Executing ${toolName} in ${executionTime}ms, result: %O`,
- executionResult,
- );
-
- // Publish tool execution result event
- await streamManager.publishStreamEvent(operationId, {
- data: {
- executionTime,
- isSuccess,
- attempts: execution.attempts,
- maxAttempts: TOOL_MAX_RETRIES + 1,
- payload,
- phase: 'tool_execution',
- result: executionResult,
- },
- stepIndex,
- type: 'tool_end',
- });
-
- // Finally persist to database. In resumption mode (skipCreateToolMessage),
- // the pending tool message already exists from request_human_approve, so
- // we update it in-place rather than inserting a new row β€” inserting would
- // either duplicate the tool_call_id or violate parent_id FK ().
- let toolMessageId: string | undefined;
- try {
- if (payload.skipCreateToolMessage) {
- toolMessageId = payload.parentMessageId;
- await ctx.messageModel.updateToolMessage(toolMessageId, {
- content: executionResult.content,
- metadata: { toolExecutionTimeMs: executionTime },
- pluginError: executionResult.error,
- pluginState: executionResult.state,
- });
- log(
- '[%s:%d] Updated existing tool message %s (skipCreateToolMessage)',
- operationId,
- stepIndex,
- toolMessageId,
- );
- } else {
- const toolMessage = await ctx.messageModel.create({
- agentId: state.metadata!.agentId!,
- content: executionResult.content,
- groupId: state.metadata?.groupId ?? undefined,
- metadata: { toolExecutionTimeMs: executionTime },
- parentId: payload.parentMessageId,
- plugin: chatToolPayload as any,
- pluginError: executionResult.error,
- pluginState: executionResult.state,
- role: 'tool',
- threadId: state.metadata?.threadId,
- tool_call_id: chatToolPayload.id,
- topicId: state.metadata?.topicId,
- });
- toolMessageId = toolMessage.id;
- }
- } catch (error) {
- console.error('[StreamingToolExecutor] Failed to persist tool message: %O', error);
- // Normalize BEFORE publishing so clients (which treat `error` stream
- // events as terminal and surface `event.data.error` directly) see the
- // typed business error, not the raw SQL / driver text.
- const fatal = isMidOperationReferenceMissingError(error)
- ? createConversationParentMissingError(payload.parentMessageId, error)
- : error instanceof Error
- ? error
- : new Error(String(error));
- await streamManager.publishStreamEvent(operationId, {
- data: formatErrorEventData(fatal, 'tool_message_persist'),
- stepIndex,
- type: 'error',
- });
- // Mark so the outer catch (which normally converts tool-exec errors
- // into event records and returns the unchanged state) re-throws.
- throw markPersistFatal(fatal);
- }
-
- const newState = structuredClone(state);
-
- // Keep plugin/pluginState on the in-state copy: the batch executor
- // refreshes state.messages from full DB rows, but this single-tool path
- // never does β€” without these fields a later step could not extract the
- // skill activation this call just produced (activatedSkills above).
- newState.messages.push({
- content: executionResult.content,
- plugin: chatToolPayload,
- pluginState: executionResult.state,
- role: 'tool',
- tool_call_id: chatToolPayload.id,
- });
-
- events.push({ id: chatToolPayload.id, result: executionResult, type: 'tool_result' });
-
- // Get tool unit price
- const toolCost = TOOL_PRICING[toolName] || 0;
-
- // Use UsageCounter to uniformly accumulate tool usage
- const { usage, cost } = UsageCounter.accumulateTool({
- cost: newState.cost,
- executionTime,
- success: isSuccess,
- toolCost,
- toolName,
- usage: newState.usage,
- });
-
- newState.usage = usage;
- if (cost) newState.cost = cost;
-
- // Persist ToolsActivator discovery results to state.activatedStepTools
- const discoveredTools = executionResult.state?.activatedTools as
- Array<{ identifier: string }> | undefined;
- if (discoveredTools?.length) {
- const existingIds = new Set(
- (newState.activatedStepTools ?? []).map((t: { id: string }) => t.id),
- );
- const newActivations = discoveredTools
- .filter((t) => !existingIds.has(t.identifier))
- .map((t) => ({
- activatedAtStep: state.stepCount,
- id: t.identifier,
- manifest: effectiveManifestMap[t.identifier],
- source: 'discovery' as const,
- }));
-
- if (newActivations.length > 0) {
- newState.activatedStepTools = [
- ...(newState.activatedStepTools ?? []),
- ...newActivations,
- ];
-
- log(
- `[${operationLogId}] Persisted %d tool activations to state: %o`,
- newActivations.length,
- newActivations.map((a) => a.id),
- );
- }
- }
-
- // Find current tool statistics
- const currentToolStats = usage.tools.byTool.find((t) => t.name === toolName);
-
- // Log usage information
- log(
- `[${operationLogId}][tool usage] %s: calls=%d, time=%dms, success=%s, cost=$%s`,
- toolName,
- currentToolStats?.calls || 0,
- executionTime,
- isSuccess,
- toolCost.toFixed(4),
- );
-
- log('[%s:%d] Tool execution completed', operationId, stepIndex);
-
- // When a legacy callAgent task result carries execSubAgent / execSubAgents
- // state, the GeneralChatAgent needs `stop: true` in the payload to detect
- // it and emit the matching exec_sub_agent / exec_sub_agents instruction.
- // Without this flag the agent falls through to the normal LLM-call path
- // and the background agent run is never spawned.
- const legacyAgentInvocationStateType = executionResult.state?.type as string | undefined;
- const isLegacyAgentInvocationState =
- legacyAgentInvocationStateType === 'execSubAgent' ||
- legacyAgentInvocationStateType === 'execSubAgents';
-
- executeToolSpan.setAttributes(
- buildExecuteToolResultAttributes({ attempts: execution.attempts, success: isSuccess }),
- );
-
- return {
- events,
- newState,
- nextContext: {
- payload: {
- data: executionResult,
- executionTime,
- isSuccess,
- // Pass tool message ID as parentMessageId for the next LLM call
- parentMessageId: toolMessageId,
- ...(isLegacyAgentInvocationState && { stop: true }),
- toolCall: chatToolPayload,
- toolCallId: chatToolPayload.id,
- },
- phase: 'tool_result',
- session: {
- eventCount: events.length,
- messageCount: newState.messages.length,
- sessionId: operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- stepUsage: {
- cost: toolCost,
- toolName,
- unitPrice: toolCost,
- usageCount: 1,
- },
- },
- };
- } catch (error) {
- executeToolSpan.recordException(error as Error);
- executeToolSpan.setStatus({
- code: SpanStatusCode.ERROR,
- message: error instanceof Error ? error.message : String(error),
- });
- executeToolSpan.setAttributes(buildExecuteToolResultAttributes({ success: false }));
-
- // Persist-level failures (parent FK violation etc.) must propagate so
- // the step fails β€” otherwise the swallow-and-continue path keeps
- // running the agent on a broken conversation chain. See .
- if (isPersistFatal(error)) throw error;
-
- if (ctx.hookDispatcher) {
- ctx.hookDispatcher
- .dispatch(
- operationId,
- 'onToolCallError',
- {
- apiName: chatToolPayload.apiName,
- args: parsedArgs,
- callIndex,
- error: error instanceof Error ? error.message : String(error),
- identifier: chatToolPayload.identifier,
- operationId,
- stepIndex,
- userId: ctx.userId,
- },
- state.metadata?._hooks,
- )
- .catch(() => {});
- }
-
- // Publish tool execution error event
- await streamManager.publishStreamEvent(operationId, {
- data: formatErrorEventData(error, 'tool_execution'),
- stepIndex,
- type: 'error',
- });
-
- events.push({ error, type: 'error' });
-
- console.error(
- `[StreamingToolExecutor] Tool execution failed for operation ${operationId}:${stepIndex}:`,
- error,
- );
-
- return {
- events,
- newState: state, // State unchanged
- };
- }
- } finally {
- executeToolSpan.end();
- }
- };
diff --git a/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts b/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts
deleted file mode 100644
index 82e5d3de1b1..00000000000
--- a/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts
+++ /dev/null
@@ -1,668 +0,0 @@
-import {
- type AgentEvent,
- type AgentInstruction,
- executeToolWithRetry,
- extractActivatedSkillsFromMessages,
- type InstructionExecutor,
- UsageCounter,
-} from '@lobechat/agent-runtime';
-import { parse } from '@lobechat/conversation-flow';
-import { SpanStatusCode } from '@lobechat/observability-otel/api';
-import {
- buildExecuteToolAttributes,
- buildExecuteToolResultAttributes,
- executeToolSpanName,
- tracer as agentRuntimeTracer,
-} from '@lobechat/observability-otel/modules/agent-runtime';
-import { type ChatToolPayload } from '@lobechat/types';
-
-import { isDeviceCapablePlan } from '@/helpers/executionTarget';
-import {
- type DeviceAccessReason,
- isDeviceToolIdentifier,
- logDeviceToolAudit,
-} from '@/server/services/aiAgent/deviceToolAudit';
-import { type ToolExecutionResultResponse } from '@/server/services/toolExecution';
-
-import { type RuntimeExecutorContext } from '../context';
-import { dispatchClientTool } from '../dispatchClientTool';
-import {
- archiveRuntimeToolResult,
- buildPostProcessUrl,
- buildServerAgentMemberRunner,
- buildServerVirtualSubAgentRunner,
- GEN_AI_FUNCTION_TOOL_TYPE,
- isOperationInterrupted,
- log,
- TOOL_MAX_RETRIES,
- TOOL_PRICING,
-} from '../executorHelpers';
-import { formatErrorEventData } from '../formatErrorEventData';
-import {
- createConversationParentMissingError,
- isMidOperationReferenceMissingError,
- isPersistFatal,
- markPersistFatal,
-} from '../messagePersistErrors';
-import { resolveToolTimeoutMs } from '../resolveToolTimeout';
-import { resolveRunActiveDeviceId } from './resolveRunActiveDeviceId';
-import { resolveRunProjectSkills } from './resolveRunProjectSkills';
-
-export const callToolsBatch =
- (ctx: RuntimeExecutorContext): InstructionExecutor =>
- async (instruction, state) => {
- const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tools_batch' }>;
- const { parentMessageId, toolsCalling } = payload;
- const { operationId, stepIndex, streamManager, toolExecutionService } = ctx;
- const events: AgentEvent[] = [];
-
- const operationLogId = `${operationId}:${stepIndex}`;
- log(
- `[${operationLogId}][call_tools_batch] Starting batch execution for ${toolsCalling.length} tools`,
- );
-
- // Split client vs server tools
- const clientTools: ChatToolPayload[] = [];
- const serverTools: ChatToolPayload[] = [];
- for (const tp of toolsCalling) {
- const src =
- state.operationToolSet?.sourceMap?.[tp.identifier] ?? state.toolSourceMap?.[tp.identifier];
- if (src === 'client') {
- clientTools.push(tp);
- } else {
- serverTools.push(tp);
- }
- }
-
- // If all tools are client-side, pause immediately
- if (clientTools.length > 0 && serverTools.length === 0) {
- log(
- `[${operationLogId}][call_tools_batch] All ${clientTools.length} tools are client-side, pausing`,
- );
-
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'tools_calling',
- toolsCalling: clientTools as any,
- });
-
- const newState = structuredClone(state);
- newState.lastModified = new Date().toISOString();
- newState.status = 'waiting_for_async_tool';
- newState.interruption = {
- canResume: true,
- interruptedAt: new Date().toISOString(),
- reason: 'client_tool_execution',
- };
- newState.pendingToolsCalling = clientTools;
-
- return {
- events: [
- {
- canResume: true,
- interruptedAt: new Date().toISOString(),
- reason: 'client_tool_execution',
- type: 'interrupted',
- },
- ],
- newState,
- };
- }
-
- // Track all tool message IDs created during execution
- const toolMessageIds: string[] = [];
- const toolResults: any[] = [];
- // Deferred (async) tools whose result is delivered out-of-band later;
- // collected here so the batch parks for them after server tools finish.
- const deferredTools: ChatToolPayload[] = [];
-
- // Execute server tools concurrently (skip client tools in mixed batch)
- const toolsToExecute = serverTools.length > 0 ? serverTools : toolsCalling;
- // Server-side equivalent of the client transport's computeStepContext
- // (mirrors the single-tool `callTool` context): skills execScript resolves
- // activated skill archives from the message history, which the raw LLM
- // args never carry. Computed once β€” identical for every tool in the batch.
- const runActivatedSkills = extractActivatedSkillsFromMessages(state.messages);
- await Promise.all(
- toolsToExecute.map(async (chatToolPayload: ChatToolPayload) => {
- const toolName = `${chatToolPayload.identifier}/${chatToolPayload.apiName}`;
-
- // Publish tool execution start event
- await streamManager.publishStreamEvent(operationId, {
- data: { parentMessageId, toolCalling: chatToolPayload },
- stepIndex,
- type: 'tool_start',
- });
-
- const batchToolName = `${chatToolPayload.identifier}/${chatToolPayload.apiName}`;
- const batchExistingStats = state.usage?.tools?.byTool?.find(
- (t) => t.name === batchToolName,
- );
- const batchCallIndex = (batchExistingStats?.calls ?? 0) + 1;
- let batchParsedArgs: Record<string, any> = {};
- try {
- batchParsedArgs =
- typeof chatToolPayload.arguments === 'string'
- ? JSON.parse(chatToolPayload.arguments)
- : (chatToolPayload.arguments ?? {});
- } catch {
- // Keep malformed tool arguments as an empty preview payload; execution still uses raw args.
- }
-
- // OTel execute_tool span β€” one per tool inside the concurrent batch.
- const batchToolSourceForSpan =
- state.operationToolSet?.sourceMap?.[chatToolPayload.identifier] ??
- state.toolSourceMap?.[chatToolPayload.identifier];
- const batchExecuteToolSpan = agentRuntimeTracer.startSpan(executeToolSpanName(toolName), {
- attributes: buildExecuteToolAttributes({
- operationId,
- stepIndex,
- toolCallId: chatToolPayload.id,
- toolName,
- toolSource: batchToolSourceForSpan,
- toolType: GEN_AI_FUNCTION_TOOL_TYPE,
- }),
- });
-
- try {
- try {
- log(`[${operationLogId}] Executing tool ${toolName} ...`);
- // Build effective manifest map (operation + step-level activations)
- const batchManifestMap = {
- ...(state.operationToolSet?.manifestMap ?? state.toolManifestMap),
- ...Object.fromEntries(
- (state.activatedStepTools ?? [])
- .filter((a) => a.manifest)
- .map((a) => [a.id, a.manifest!]),
- ),
- };
-
- const batchAgentConfig = state.metadata?.agentConfig;
-
- const canDispatchToClient =
- chatToolPayload.executor === 'client' &&
- typeof streamManager.sendToolExecute === 'function';
-
- let batchToolCallMocked = false;
- const batchHookResult = ctx.hookDispatcher
- ? await (async () => {
- ctx
- .hookDispatcher!.dispatch(
- operationId,
- 'beforeToolCall',
- {
- apiName: chatToolPayload.apiName,
- args: batchParsedArgs,
- callIndex: batchCallIndex,
- identifier: chatToolPayload.identifier,
- operationId,
- stepIndex,
- userId: ctx.userId,
- },
- state.metadata?._hooks,
- )
- .catch(() => {});
- return ctx.hookDispatcher!.dispatchBeforeToolCall(operationId, {
- apiName: chatToolPayload.apiName,
- args: batchParsedArgs,
- callIndex: batchCallIndex,
- identifier: chatToolPayload.identifier,
- stepIndex,
- });
- })()
- : null;
-
- if (isDeviceToolIdentifier(chatToolPayload.identifier) && !batchHookResult?.isMocked) {
- const policy = state.metadata?.deviceAccessPolicy as
- { canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
- logDeviceToolAudit({
- apiName: chatToolPayload.apiName,
- botContext: state.metadata?.botContext,
- canUseDevice: policy?.canUseDevice ?? true,
- messageId: state.metadata?.sourceMessageId,
- operationId,
- reason: policy?.reason ?? 'first-party',
- toolIdentifier: chatToolPayload.identifier,
- topicId: ctx.topicId,
- userId: ctx.userId,
- });
- }
-
- let execution: { result: ToolExecutionResultResponse; attempts: number };
- if (batchHookResult?.isMocked) {
- log(`[${operationLogId}] Tool ${toolName} mocked by beforeToolCall hook`);
- batchToolCallMocked = true;
- execution = {
- attempts: 0,
- result: { content: batchHookResult.content, executionTime: 0, success: true },
- };
- } else if (canDispatchToClient) {
- log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);
- const timeoutMs = resolveToolTimeoutMs({
- apiName: chatToolPayload.apiName,
- args: batchParsedArgs,
- manifest: batchManifestMap[chatToolPayload.identifier],
- });
- const dispatchResult = await dispatchClientTool(chatToolPayload, {
- operationId,
- streamManager,
- timeoutMs,
- });
- execution = { attempts: 1, result: dispatchResult };
- } else {
- // Inject source from sourceMap so BuiltinToolsExecutor can route
- // lobehubSkill / composio tools correctly (LLM responses don't carry source)
- const batchToolSource =
- state.operationToolSet?.sourceMap?.[chatToolPayload.identifier] ??
- state.toolSourceMap?.[chatToolPayload.identifier];
- if (batchToolSource && !chatToolPayload.source) {
- chatToolPayload.source = batchToolSource;
- }
-
- const timeoutMs = resolveToolTimeoutMs({
- apiName: chatToolPayload.apiName,
- args: batchParsedArgs,
- manifest: batchManifestMap[chatToolPayload.identifier],
- });
-
- execution = await executeToolWithRetry(
- () =>
- toolExecutionService.executeTool(chatToolPayload, {
- activatedSkills: runActivatedSkills,
- // Plan/policy-filtered: a preset or stale metadata id must not route
- // tool execution (e.g. skills execScript) onto a device the resolved
- // plan didn't authorize.
- activeDeviceId: resolveRunActiveDeviceId(state.metadata),
- agentId: state.metadata?.agentId,
- agentMember: buildServerAgentMemberRunner(
- ctx,
- state,
- chatToolPayload,
- payload.parentMessageId,
- ),
- // Assistant message owning this tool call (β‰  source user message).
- assistantMessageId: payload.parentMessageId,
- deviceCapable: state.metadata?.executionPlan
- ? isDeviceCapablePlan(state.metadata.executionPlan)
- : undefined,
- documentId: state.metadata?.documentId,
- execSubAgent: ctx.execSubAgent,
- executionTimeoutMs: timeoutMs,
- groupId: state.metadata?.groupId,
- isSubAgent: state.metadata?.isSubAgent === true,
- memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,
- messageId: state.metadata?.sourceMessageId,
- operationId,
- // Mirrors the single-tool `callTool` context: without these
- // a batched device execScript loses the SKILL.md / selected
- // working directory and runs from the daemon's default cwd.
- projectSkills: resolveRunProjectSkills(state.metadata),
- scope: state.metadata?.scope,
- serverDB: ctx.serverDB,
- skipResultTruncation: true,
- subAgent: buildServerVirtualSubAgentRunner(
- ctx,
- state,
- chatToolPayload,
- payload.parentMessageId,
- ),
- taskId: state.metadata?.taskId,
- threadId: state.metadata?.threadId,
- toolCallId: chatToolPayload.id,
- toolManifestMap: batchManifestMap,
- toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,
- topicId: ctx.topicId,
- userId: ctx.userId,
- // Device-bound cwd folded into deviceSystemInfo at operation
- // creation; resume-safe via computeDeviceContext (recovers it
- // from the prior tool message's pluginState.metadata).
- workingDirectory: state.metadata?.deviceSystemInfo?.workingDirectory,
- workspaceId: state.metadata?.workspaceId ?? ctx.workspaceId,
- }),
- {
- isInterrupted: () => isOperationInterrupted(ctx),
- maxRetries: TOOL_MAX_RETRIES,
- onRetry: ({ attempt, kind, maxAttempts }) =>
- log(
- '[%s] Tool %s failed with kind=%s (attempt %d/%d), retrying ...',
- operationLogId,
- toolName,
- kind,
- attempt,
- maxAttempts,
- ),
- },
- );
- }
-
- // Deferred (async) tool: executor created a pending placeholder and
- // the real result arrives out-of-band. Skip the tool_result write;
- // the batch parks for it after all server tools settle.
- if (execution.result.deferred) {
- log(`[${operationLogId}] Tool ${toolName} deferred; will park after batch`);
- deferredTools.push(chatToolPayload);
- batchExecuteToolSpan.setAttributes(
- buildExecuteToolResultAttributes({ attempts: execution.attempts, success: true }),
- );
- return;
- }
-
- const executionResult = await archiveRuntimeToolResult(execution.result, {
- agentId: state.metadata?.agentId,
- identifier: chatToolPayload.identifier,
- limit: batchAgentConfig?.chatConfig?.toolResultMaxLength,
- serverDB: ctx.serverDB,
- toolCallId: chatToolPayload.id,
- topicId: ctx.topicId ?? state.metadata?.topicId,
- userId: ctx.userId,
- workspaceId: state.metadata?.workspaceId ?? ctx.workspaceId,
- });
- const executionTime = executionResult.executionTime;
- const isSuccess = executionResult.success;
- if (ctx.hookDispatcher) {
- ctx.hookDispatcher
- .dispatch(
- operationId,
- 'afterToolCall',
- {
- apiName: chatToolPayload.apiName,
- args: batchParsedArgs,
- callIndex: batchCallIndex,
- content: executionResult.content,
- executionTimeMs: executionTime,
- identifier: chatToolPayload.identifier,
- mocked: batchToolCallMocked,
- operationId,
- stepIndex,
- success: isSuccess,
- userId: ctx.userId,
- },
- state.metadata?._hooks,
- )
- .catch(() => {});
- }
- log(
- `[${operationLogId}] Executed ${toolName} in ${executionTime}ms, success: ${isSuccess}`,
- );
-
- // Publish tool execution result event
- await streamManager.publishStreamEvent(operationId, {
- data: {
- executionTime,
- isSuccess,
- attempts: execution.attempts,
- maxAttempts: TOOL_MAX_RETRIES + 1,
- payload: { parentMessageId, toolCalling: chatToolPayload },
- phase: 'tool_execution',
- result: executionResult,
- },
- stepIndex,
- type: 'tool_end',
- });
-
- // Create tool message in database
- try {
- const toolMessage = await ctx.messageModel.create({
- agentId: state.metadata!.agentId!,
- content: executionResult.content,
- groupId: state.metadata?.groupId ?? undefined,
- metadata: { toolExecutionTimeMs: executionTime },
- parentId: parentMessageId,
- plugin: chatToolPayload as any,
- pluginError: executionResult.error,
- pluginState: executionResult.state,
- role: 'tool',
- threadId: state.metadata?.threadId,
- tool_call_id: chatToolPayload.id,
- topicId: state.metadata?.topicId,
- });
- toolMessageIds.push(toolMessage.id);
- log(`[${operationLogId}] Created tool message ${toolMessage.id} for ${toolName}`);
- } catch (error) {
- console.error(
- `[${operationLogId}] Failed to create tool message for ${toolName}:`,
- error,
- );
- // Normalize BEFORE publishing β€” clients treat `error` stream
- // events as terminal and surface `event.data.error` directly, so
- // a raw SQL error here would leak driver text to the user before
- // the ConversationParentMissing throw is consumed. See .
- const fatal = isMidOperationReferenceMissingError(error)
- ? createConversationParentMissingError(parentMessageId, error)
- : error instanceof Error
- ? error
- : new Error(String(error));
- await streamManager.publishStreamEvent(operationId, {
- data: formatErrorEventData(fatal, 'tool_message_persist'),
- stepIndex,
- type: 'error',
- });
- // Marker so the outer catch (which normally just records
- // per-tool exec errors) knows to propagate this one.
- throw markPersistFatal(fatal);
- }
-
- // Collect tool result
- toolResults.push({
- data: executionResult,
- executionTime,
- isSuccess,
- toolCall: chatToolPayload,
- toolCallId: chatToolPayload.id,
- });
-
- events.push({ id: chatToolPayload.id, result: executionResult, type: 'tool_result' });
-
- // Collect per-tool usage for post-batch accumulation
- const toolCost = TOOL_PRICING[toolName] || 0;
- toolResults.at(-1).usageParams = {
- executionTime,
- success: isSuccess,
- toolCost,
- toolName,
- };
-
- batchExecuteToolSpan.setAttributes(
- buildExecuteToolResultAttributes({
- attempts: execution.attempts,
- success: isSuccess,
- }),
- );
- } catch (error) {
- batchExecuteToolSpan.recordException(error as Error);
- batchExecuteToolSpan.setStatus({
- code: SpanStatusCode.ERROR,
- message: error instanceof Error ? error.message : String(error),
- });
- batchExecuteToolSpan.setAttributes(
- buildExecuteToolResultAttributes({ success: false }),
- );
-
- // Persist-level failures (e.g. parent FK violations) must propagate
- // so the whole batch short-circuits. Without this the fallback to
- // the already-deleted parent triggers another FK on the next step.
- if (isPersistFatal(error)) {
- throw error;
- }
-
- if (ctx.hookDispatcher) {
- ctx.hookDispatcher
- .dispatch(
- operationId,
- 'onToolCallError',
- {
- apiName: chatToolPayload.apiName,
- args: batchParsedArgs,
- callIndex: batchCallIndex,
- error: error instanceof Error ? error.message : String(error),
- identifier: chatToolPayload.identifier,
- operationId,
- stepIndex,
- userId: ctx.userId,
- },
- state.metadata?._hooks,
- )
- .catch(() => {});
- }
-
- console.error(`[${operationLogId}] Tool execution failed for ${toolName}:`, error);
-
- // Publish error event
- await streamManager.publishStreamEvent(operationId, {
- data: formatErrorEventData(error, 'tool_execution'),
- stepIndex,
- type: 'error',
- });
-
- events.push({ error, type: 'error' });
- }
- } finally {
- batchExecuteToolSpan.end();
- }
- }),
- );
-
- log(
- `[${operationLogId}][call_tools_batch] All tools executed, created ${toolMessageIds.length} tool messages`,
- );
-
- // Accumulate tool usage sequentially after all tools have finished
- const newState = structuredClone(state);
- for (const result of toolResults) {
- if (result.usageParams) {
- const { usage, cost } = UsageCounter.accumulateTool({
- ...result.usageParams,
- cost: newState.cost,
- usage: newState.usage,
- });
- newState.usage = usage;
- if (cost) newState.cost = cost;
- }
- }
-
- // Persist ToolsActivator discovery results from batch tool executions
- const batchEffectiveManifestMap = {
- ...(state.operationToolSet?.manifestMap ?? state.toolManifestMap),
- ...Object.fromEntries(
- (state.activatedStepTools ?? []).filter((a) => a.manifest).map((a) => [a.id, a.manifest!]),
- ),
- };
- const existingActivationIds = new Set(
- (newState.activatedStepTools ?? []).map((t: { id: string }) => t.id),
- );
- for (const result of toolResults) {
- const discovered = result.data?.state?.activatedTools as
- Array<{ identifier: string }> | undefined;
- if (discovered?.length) {
- const newActivations = discovered
- .filter((t) => !existingActivationIds.has(t.identifier))
- .map((t) => ({
- activatedAtStep: state.stepCount,
- id: t.identifier,
- manifest: batchEffectiveManifestMap[t.identifier],
- source: 'discovery' as const,
- }));
-
- for (const activation of newActivations) {
- existingActivationIds.add(activation.id);
- }
-
- if (newActivations.length > 0) {
- newState.activatedStepTools = [...(newState.activatedStepTools ?? []), ...newActivations];
- }
- }
- }
-
- // Refresh messages from database to ensure state is in sync
-
- // Query latest messages from database
- // Must pass agentId to ensure correct query scope, otherwise when topicId is undefined,
- // the query will use isNull(topicId) condition which won't find messages with actual topicId
- //
- // postProcessUrl resolves keys in imageList/videoList/fileList to external URLs;
- // without it the next LLM call sees raw keys and providers reject them.
- const latestMessages = await ctx.messageModel.query(
- {
- agentId: state.metadata?.agentId,
- // Group runs must pass groupId, else the query falls into the standard
- // branch (`groupId IS NULL`) and returns zero group messages β€” the next
- // call_llm step then gets an empty context and the provider rejects it
- // ("at least one message is required").
- groupId: state.metadata?.groupId,
- threadId: state.metadata?.threadId,
- topicId: state.metadata?.topicId,
- },
- { postProcessUrl: buildPostProcessUrl(ctx) },
- );
-
- // Use conversation-flow parse to resolve branching into linear flat list
- // parse() handles assistantGroup, compare, supervisor, etc. virtual message types
- const { flatList } = parse(latestMessages);
- newState.messages = flatList;
-
- log(
- `[${operationLogId}][call_tools_batch] Refreshed ${newState.messages.length} messages from database`,
- );
-
- // Get the last tool message ID as parentMessageId for next LLM call
- const lastToolMessageId = toolMessageIds.at(-1);
-
- // Park if any tools still owe an out-of-band result: client tools (run on
- // the client) and/or deferred async tools (e.g. sub-agents). The operation
- // resumes once every pending tool's result is delivered.
- const pendingTools = [...deferredTools, ...clientTools];
- if (pendingTools.length > 0) {
- // Prefer the async-tool reason when any deferred tool is present; the
- // individual pending payloads still carry their own identity for the
- // resume gate.
- const pauseReason = deferredTools.length > 0 ? 'async_tool' : 'client_tool_execution';
- log(
- `[${operationLogId}][call_tools_batch] Pausing after ${serverTools.length} server tools: ${deferredTools.length} deferred + ${clientTools.length} client`,
- );
-
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'tools_calling',
- toolsCalling: pendingTools as any,
- });
-
- newState.status = 'waiting_for_async_tool';
- newState.interruption = {
- canResume: true,
- interruptedAt: new Date().toISOString(),
- reason: pauseReason,
- };
- newState.pendingToolsCalling = pendingTools;
-
- return {
- events: [
- ...events,
- {
- canResume: true,
- interruptedAt: new Date().toISOString(),
- reason: pauseReason,
- type: 'interrupted',
- },
- ],
- newState,
- };
- }
-
- return {
- events,
- newState,
- nextContext: {
- payload: {
- parentMessageId: lastToolMessageId ?? parentMessageId,
- toolCount: toolsCalling.length,
- toolResults,
- },
- phase: 'tools_batch_result',
- session: {
- eventCount: events.length,
- messageCount: newState.messages.length,
- sessionId: operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- },
- };
- };
diff --git a/packages/agent-runtime/src/executors/index.ts b/packages/agent-runtime/src/executors/index.ts
index 77732cf0ffb..02472d82247 100644
--- a/packages/agent-runtime/src/executors/index.ts
+++ b/packages/agent-runtime/src/executors/index.ts
@@ -1,3 +1,4 @@
export * from './finish';
export * from './humanApprove';
export * from './resolveTools';
+export * from './tool';
diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.ts
new file mode 100644
index 00000000000..d207260f47b
--- /dev/null
+++ b/packages/agent-runtime/src/executors/tool.test.ts
@@ -0,0 +1,232 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { AgentRuntimeHost } from '../transport';
+import type { AgentInstruction, AgentState } from '../types';
+import { callTool, callToolsBatch } from './tool';
+
+const createCost = () => ({
+ calculatedAt: '2026-07-09T00:00:00.000Z',
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ total: 0,
+});
+
+const createUsage = () => ({
+ 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 },
+});
+
+const createState = (overrides?: Partial<AgentState>): AgentState => ({
+ cost: createCost(),
+ createdAt: '2026-07-09T00:00:00.000Z',
+ lastModified: '2026-07-09T00:00:00.000Z',
+ maxSteps: 100,
+ messages: [],
+ metadata: {
+ agentId: 'agent-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ operationId: 'op-1',
+ status: 'running',
+ stepCount: 0,
+ toolManifestMap: {},
+ usage: createUsage(),
+ ...overrides,
+});
+
+const createToolCall = (id = 'tool-call-1', identifier = 'web-search') => ({
+ apiName: 'search',
+ arguments: '{"query":"test"}',
+ id,
+ identifier,
+ type: 'default' as const,
+});
+
+describe('tool executors', () => {
+ let createToolMessage: ReturnType<typeof vi.fn>;
+ let publishChunk: ReturnType<typeof vi.fn>;
+ let publishError: ReturnType<typeof vi.fn>;
+ let publishEvent: ReturnType<typeof vi.fn>;
+ let query: ReturnType<typeof vi.fn>;
+ let runTool: ReturnType<typeof vi.fn>;
+ let host: AgentRuntimeHost;
+
+ beforeEach(() => {
+ createToolMessage = vi.fn().mockResolvedValue({ id: 'tool-msg-1' });
+ publishChunk = vi.fn().mockResolvedValue(undefined);
+ publishError = vi.fn().mockResolvedValue(undefined);
+ publishEvent = vi.fn().mockResolvedValue(undefined);
+ query = vi.fn().mockResolvedValue([{ content: 'refreshed', id: 'msg-1', role: 'user' }]);
+ runTool = vi.fn().mockResolvedValue({
+ attempts: 1,
+ result: {
+ content: 'Tool result',
+ executionTime: 100,
+ state: {},
+ success: true,
+ },
+ });
+
+ host = {
+ operation: {
+ operationId: 'op-1',
+ stepIndex: 2,
+ },
+ transports: {
+ messages: {
+ createAssistantMessage: vi.fn(),
+ createToolMessage,
+ deleteMessage: vi.fn(),
+ findById: vi.fn(),
+ query,
+ update: vi.fn(),
+ updatePluginState: vi.fn(),
+ updateToolMessage: vi.fn(),
+ },
+ stream: {
+ publishChunk,
+ publishError,
+ publishEvent,
+ },
+ tools: {
+ getCost: vi.fn().mockReturnValue(0),
+ handleError: vi.fn(),
+ maxRetries: 2,
+ run: runTool,
+ },
+ },
+ } as unknown as AgentRuntimeHost;
+ });
+
+ it('executes a single tool, persists the result, and advances to tool_result', async () => {
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolCalling: createToolCall(),
+ },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(host)(instruction, createState());
+
+ expect(runTool).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'tool-call-1' }),
+ expect.objectContaining({
+ callIndex: 1,
+ parentMessageId: 'assistant-msg-1',
+ parsedArgs: { query: 'test' },
+ toolName: 'web-search/search',
+ }),
+ );
+ expect(createToolMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'Tool result',
+ metadata: { toolExecutionTimeMs: 100 },
+ parentId: 'assistant-msg-1',
+ role: 'tool',
+ tool_call_id: 'tool-call-1',
+ }),
+ );
+ expect(publishEvent).toHaveBeenCalledWith(expect.objectContaining({ type: 'tool_start' }));
+ expect(publishEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({ attempts: 1, isSuccess: true }),
+ type: 'tool_end',
+ }),
+ );
+ expect(result.nextContext?.phase).toBe('tool_result');
+ expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'tool-msg-1' });
+ expect(result.newState.usage.tools.totalCalls).toBe(1);
+ });
+
+ it('parks single client-source tools without invoking the transport runner', async () => {
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolCalling: createToolCall('client-call', 'client-tool'),
+ },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(host)(
+ instruction,
+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),
+ );
+
+ expect(runTool).not.toHaveBeenCalled();
+ expect(publishChunk).toHaveBeenCalledWith(
+ expect.objectContaining({
+ chunkType: 'tools_calling',
+ toolsCalling: [expect.objectContaining({ id: 'client-call' })],
+ }),
+ );
+ expect(result.newState.status).toBe('waiting_for_async_tool');
+ expect(result.events).toContainEqual(
+ expect.objectContaining({ reason: 'client_tool_execution', type: 'interrupted' }),
+ );
+ });
+
+ it('executes server tools in a mixed batch then parks for client tools', async () => {
+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolsCalling: [createToolCall('server-call'), createToolCall('client-call', 'client-tool')],
+ },
+ type: 'call_tools_batch',
+ };
+
+ const result = await callToolsBatch(host)(
+ instruction,
+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),
+ );
+
+ expect(runTool).toHaveBeenCalledTimes(1);
+ expect(createToolMessage).toHaveBeenCalledTimes(1);
+ expect(query).toHaveBeenCalledWith(
+ {
+ agentId: 'agent-1',
+ groupId: undefined,
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ { flatten: true, resolveAssetUrls: true },
+ );
+ expect(result.newState.status).toBe('waiting_for_async_tool');
+ expect(result.newState.pendingToolsCalling).toEqual([
+ expect.objectContaining({ id: 'client-call' }),
+ ]);
+ expect(result.events).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: 'server-call', type: 'tool_result' }),
+ expect.objectContaining({ reason: 'client_tool_execution', type: 'interrupted' }),
+ ]),
+ );
+ });
+
+ it('publishes and rethrows tool-message persist errors', async () => {
+ const error = new Error('database failed');
+ createToolMessage.mockRejectedValueOnce(error);
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolCalling: createToolCall(),
+ },
+ type: 'call_tool',
+ };
+
+ await expect(callTool(host)(instruction, createState())).rejects.toThrow('database failed');
+ expect(publishError).toHaveBeenCalledWith({
+ error,
+ phase: 'tool_message_persist',
+ stepIndex: 2,
+ });
+ });
+});
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
new file mode 100644
index 00000000000..1f9e27d7fbb
--- /dev/null
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -0,0 +1,637 @@
+import type { ChatToolPayload } from '@lobechat/types';
+
+import { UsageCounter } from '../core';
+import type { AgentRuntimeHost, ToolRunContext, ToolRunResult } from '../transport';
+import type { AgentEvent, AgentInstruction, AgentState, InstructionExecutor } from '../types';
+import { extractActivatedSkillsFromMessages } from '../utils';
+
+const TOOL_EXECUTION_PHASE = 'tool_execution';
+const TOOL_MESSAGE_PERSIST_PHASE = 'tool_message_persist';
+const DEFAULT_TOOL_MAX_RETRIES = 2;
+
+const persistFatalErrors = new WeakSet<object>();
+
+interface ToolResultEntry {
+ data: ToolRunResult;
+ executionTime: number;
+ isSuccess: boolean;
+ toolCall: ChatToolPayload;
+ toolCallId: string;
+ usageParams?: {
+ executionTime: number;
+ success: boolean;
+ toolCost: number;
+ toolName: string;
+ };
+}
+
+const nowIso = () => new Date().toISOString();
+
+const markPersistFatal = <T>(error: T): T => {
+ if (error && typeof error === 'object') persistFatalErrors.add(error);
+ return error;
+};
+
+const isPersistFatal = (error: unknown) =>
+ !!error && typeof error === 'object' && persistFatalErrors.has(error);
+
+const getErrorType = (error: unknown): string | undefined => {
+ if (!error || typeof error !== 'object') return;
+
+ const value = (error as { errorType?: unknown; name?: unknown; type?: unknown }).errorType;
+ if (typeof value === 'string' || typeof value === 'number') return String(value);
+
+ const type = (error as { type?: unknown }).type;
+ if (typeof type === 'string' || typeof type === 'number') return String(type);
+
+ const name = error instanceof Error ? error.name : undefined;
+ return name || undefined;
+};
+
+const getErrorMessage = (error: unknown): string => {
+ if (error instanceof Error && error.message) return error.message;
+ if (typeof error === 'string' && error) return error;
+ if (error && typeof error === 'object') {
+ const message = (error as { message?: unknown }).message;
+ if (typeof message === 'string' && message) return message;
+ }
+ return 'Unknown error';
+};
+
+const requireToolTransport = (host: AgentRuntimeHost) => {
+ const tools = host.transports.tools;
+ if (!tools) {
+ throw new Error('ToolTransport is required for tool executors');
+ }
+ return tools;
+};
+
+const toolNameOf = (tool: ChatToolPayload) => `${tool.identifier}/${tool.apiName}`;
+
+const resolveToolSource = (state: AgentState, tool: ChatToolPayload): string | undefined =>
+ state.operationToolSet?.sourceMap?.[tool.identifier] ?? state.toolSourceMap?.[tool.identifier];
+
+const parseToolArgs = (tool: ChatToolPayload): Record<string, unknown> => {
+ try {
+ if (typeof tool.arguments === 'string') {
+ const parsed = JSON.parse(tool.arguments) as unknown;
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : {};
+ }
+
+ return tool.arguments && typeof tool.arguments === 'object'
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ } catch {
+ // Execution still receives the raw arguments; this preview is only for hooks.
+ return {};
+ }
+};
+
+const buildEffectiveManifestMap = (state: AgentState): Record<string, any> => ({
+ ...(state.operationToolSet?.manifestMap ?? state.toolManifestMap),
+ ...Object.fromEntries(
+ (state.activatedStepTools ?? [])
+ .filter((activation) => activation.manifest)
+ .map((activation) => [activation.id, activation.manifest!]),
+ ),
+});
+
+const resolveCallIndex = (state: AgentState, toolName: string) => {
+ const existingToolStats = state.usage?.tools?.byTool?.find((tool) => tool.name === toolName);
+ return (existingToolStats?.calls ?? 0) + 1;
+};
+
+const createRunContext = ({
+ host,
+ mode,
+ parentMessageId,
+ state,
+ tool,
+}: {
+ host: AgentRuntimeHost;
+ mode: ToolRunContext['mode'];
+ parentMessageId: string;
+ state: AgentState;
+ tool: ChatToolPayload;
+}): ToolRunContext => {
+ const toolName = toolNameOf(tool);
+ const toolSource = resolveToolSource(state, tool);
+ const agentConfig = state.metadata?.agentConfig as
+ { chatConfig?: { toolResultMaxLength?: number } } | undefined;
+
+ return {
+ activatedSkills: extractActivatedSkillsFromMessages(state.messages),
+ agentId: state.metadata?.agentId,
+ assistantMessageId: parentMessageId,
+ callIndex: resolveCallIndex(state, toolName),
+ effectiveManifestMap: buildEffectiveManifestMap(state),
+ groupId: state.metadata?.groupId,
+ messageId: state.metadata?.sourceMessageId,
+ mode,
+ operationId: host.operation.operationId,
+ parentMessageId,
+ parsedArgs: parseToolArgs(tool),
+ state,
+ stepIndex: host.operation.stepIndex,
+ threadId: state.metadata?.threadId,
+ toolName,
+ toolResultMaxLength: agentConfig?.chatConfig?.toolResultMaxLength,
+ toolSource,
+ topicId: host.operation.topicId ?? state.metadata?.topicId,
+ workspaceId: state.metadata?.workspaceId ?? host.operation.workspaceId,
+ };
+};
+
+const publishError = async (host: AgentRuntimeHost, error: unknown, phase: string) => {
+ const { stepIndex } = host.operation;
+
+ if (host.transports.stream.publishError) {
+ await host.transports.stream.publishError({ error, phase, stepIndex });
+ return;
+ }
+
+ await host.transports.stream.publishEvent({
+ data: {
+ error: getErrorMessage(error),
+ errorType: getErrorType(error),
+ phase,
+ },
+ stepIndex,
+ type: 'error',
+ });
+};
+
+const pauseForTools = async ({
+ host,
+ instruction,
+ reason,
+ state,
+ toolsCalling,
+}: {
+ host: AgentRuntimeHost;
+ instruction?: AgentInstruction;
+ reason: string;
+ state: AgentState;
+ toolsCalling: ChatToolPayload[];
+}) => {
+ await host.transports.stream.publishChunk({
+ chunkType: 'tools_calling',
+ stepIndex: host.operation.stepIndex,
+ toolsCalling,
+ });
+
+ const interruptedAt = nowIso();
+ const newState = structuredClone(state);
+ newState.lastModified = interruptedAt;
+ newState.status = 'waiting_for_async_tool';
+ newState.interruption = {
+ canResume: true,
+ interruptedAt,
+ ...(instruction && { interruptedInstruction: instruction }),
+ reason,
+ };
+ newState.pendingToolsCalling = toolsCalling;
+
+ return {
+ events: [
+ {
+ canResume: true,
+ interruptedAt,
+ reason,
+ type: 'interrupted' as const,
+ },
+ ],
+ newState,
+ };
+};
+
+const createToolMessage = async ({
+ host,
+ parentMessageId,
+ result,
+ state,
+ tool,
+}: {
+ host: AgentRuntimeHost;
+ parentMessageId: string;
+ result: ToolRunResult;
+ state: AgentState;
+ tool: ChatToolPayload;
+}) => {
+ try {
+ return await host.transports.messages.createToolMessage({
+ agentId: state.metadata!.agentId!,
+ content: result.content,
+ groupId: state.metadata?.groupId ?? undefined,
+ metadata: { toolExecutionTimeMs: result.executionTime ?? 0 },
+ parentId: parentMessageId,
+ plugin: tool as any,
+ pluginError: result.error,
+ pluginState: result.state,
+ role: 'tool',
+ threadId: state.metadata?.threadId,
+ tool_call_id: tool.id,
+ topicId: state.metadata?.topicId,
+ });
+ } catch (error) {
+ await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);
+ throw markPersistFatal(error);
+ }
+};
+
+const updateExistingToolMessage = async ({
+ host,
+ result,
+ toolMessageId,
+}: {
+ host: AgentRuntimeHost;
+ result: ToolRunResult;
+ toolMessageId: string;
+}) => {
+ try {
+ await host.transports.messages.updateToolMessage(toolMessageId, {
+ content: result.content,
+ metadata: { toolExecutionTimeMs: result.executionTime ?? 0 },
+ pluginError: result.error,
+ pluginState: result.state,
+ });
+ } catch (error) {
+ await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);
+ throw markPersistFatal(error);
+ }
+};
+
+const persistActivatedTools = ({
+ effectiveManifestMap,
+ newState,
+ results,
+ stepCount,
+}: {
+ effectiveManifestMap: Record<string, any>;
+ newState: AgentState;
+ results: ToolResultEntry[];
+ stepCount: number;
+}) => {
+ const existingIds = new Set((newState.activatedStepTools ?? []).map((tool) => tool.id));
+
+ for (const result of results) {
+ const discoveredTools = result.data.state?.activatedTools as
+ Array<{ identifier: string }> | undefined;
+ if (!discoveredTools?.length) continue;
+
+ const newActivations = discoveredTools
+ .filter((tool) => !existingIds.has(tool.identifier))
+ .map((tool) => ({
+ activatedAtStep: stepCount,
+ id: tool.identifier,
+ manifest: effectiveManifestMap[tool.identifier],
+ source: 'discovery' as const,
+ }));
+
+ for (const activation of newActivations) existingIds.add(activation.id);
+
+ if (newActivations.length > 0) {
+ newState.activatedStepTools = [...(newState.activatedStepTools ?? []), ...newActivations];
+ }
+ }
+};
+
+export const callTool =
+ (host: AgentRuntimeHost): InstructionExecutor =>
+ async (instruction, state) => {
+ const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tool' }>;
+ const tools = requireToolTransport(host);
+ const tool = payload.toolCalling;
+ const events: AgentEvent[] = [];
+ const runContext = createRunContext({
+ host,
+ mode: 'single',
+ parentMessageId: payload.parentMessageId,
+ state,
+ tool,
+ });
+
+ await host.transports.stream.publishEvent({
+ data: payload,
+ stepIndex: host.operation.stepIndex,
+ type: 'tool_start',
+ });
+
+ if (runContext.toolSource === 'client') {
+ return pauseForTools({
+ host,
+ instruction,
+ reason: 'client_tool_execution',
+ state,
+ toolsCalling: [tool],
+ });
+ }
+
+ try {
+ const execution = await tools.run(tool, runContext);
+
+ if (execution.result.deferred) {
+ return pauseForTools({
+ host,
+ reason: 'async_tool',
+ state,
+ toolsCalling: [tool],
+ });
+ }
+
+ const executionResult = execution.result;
+ const executionTime = executionResult.executionTime ?? 0;
+ const isSuccess = executionResult.success;
+
+ await host.transports.stream.publishEvent({
+ data: {
+ executionTime,
+ isSuccess,
+ attempts: execution.attempts,
+ maxAttempts: (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,
+ payload,
+ phase: TOOL_EXECUTION_PHASE,
+ result: executionResult,
+ },
+ stepIndex: host.operation.stepIndex,
+ type: 'tool_end',
+ });
+
+ let toolMessageId: string;
+ if (payload.skipCreateToolMessage) {
+ toolMessageId = payload.parentMessageId;
+ await updateExistingToolMessage({ host, result: executionResult, toolMessageId });
+ } else {
+ const toolMessage = await createToolMessage({
+ host,
+ parentMessageId: payload.parentMessageId,
+ result: executionResult,
+ state,
+ tool,
+ });
+ toolMessageId = toolMessage.id;
+ }
+
+ const newState = structuredClone(state);
+ newState.messages.push({
+ content: executionResult.content,
+ plugin: tool,
+ pluginState: executionResult.state,
+ role: 'tool',
+ tool_call_id: tool.id,
+ });
+ newState.lastModified = nowIso();
+
+ events.push({ id: tool.id, result: executionResult, type: 'tool_result' });
+
+ const toolCost = tools.getCost?.(runContext.toolName) ?? 0;
+ const { usage, cost } = UsageCounter.accumulateTool({
+ cost: newState.cost,
+ executionTime,
+ success: isSuccess,
+ toolCost,
+ toolName: runContext.toolName,
+ usage: newState.usage,
+ });
+
+ newState.usage = usage;
+ if (cost) newState.cost = cost;
+
+ persistActivatedTools({
+ effectiveManifestMap: runContext.effectiveManifestMap,
+ newState,
+ results: [
+ {
+ data: executionResult,
+ executionTime,
+ isSuccess,
+ toolCall: tool,
+ toolCallId: tool.id,
+ },
+ ],
+ stepCount: state.stepCount,
+ });
+
+ const legacyAgentInvocationStateType = executionResult.state?.type as string | undefined;
+ const isLegacyAgentInvocationState =
+ legacyAgentInvocationStateType === 'execSubAgent' ||
+ legacyAgentInvocationStateType === 'execSubAgents';
+
+ return {
+ events,
+ newState,
+ nextContext: {
+ payload: {
+ data: executionResult,
+ executionTime,
+ isSuccess,
+ parentMessageId: toolMessageId,
+ ...(isLegacyAgentInvocationState && { stop: true }),
+ toolCall: tool,
+ toolCallId: tool.id,
+ },
+ phase: 'tool_result',
+ session: {
+ eventCount: events.length,
+ messageCount: newState.messages.length,
+ sessionId: host.operation.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ stepUsage: {
+ cost: toolCost,
+ toolName: runContext.toolName,
+ unitPrice: toolCost,
+ usageCount: 1,
+ },
+ },
+ };
+ } catch (error) {
+ if (isPersistFatal(error)) throw error;
+
+ await tools.handleError?.(tool, error, runContext);
+ await publishError(host, error, TOOL_EXECUTION_PHASE);
+
+ events.push({ error, type: 'error' });
+
+ return {
+ events,
+ newState: state,
+ };
+ }
+ };
+
+export const callToolsBatch =
+ (host: AgentRuntimeHost): InstructionExecutor =>
+ async (instruction, state) => {
+ const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tools_batch' }>;
+ const parentMessageId = payload.parentMessageId as string;
+ const toolsCalling = payload.toolsCalling as ChatToolPayload[];
+ const tools = requireToolTransport(host);
+ const events: AgentEvent[] = [];
+ const clientTools: ChatToolPayload[] = [];
+ const serverTools: ChatToolPayload[] = [];
+
+ for (const tool of toolsCalling) {
+ if (resolveToolSource(state, tool) === 'client') clientTools.push(tool);
+ else serverTools.push(tool);
+ }
+
+ if (clientTools.length > 0 && serverTools.length === 0) {
+ return pauseForTools({
+ host,
+ reason: 'client_tool_execution',
+ state,
+ toolsCalling: clientTools,
+ });
+ }
+
+ const toolMessageIds: string[] = [];
+ const toolResults: ToolResultEntry[] = [];
+ const deferredTools: ChatToolPayload[] = [];
+ const toolsToExecute = serverTools.length > 0 ? serverTools : toolsCalling;
+
+ await Promise.all(
+ toolsToExecute.map(async (tool) => {
+ const runContext = createRunContext({ host, mode: 'batch', parentMessageId, state, tool });
+
+ await host.transports.stream.publishEvent({
+ data: { parentMessageId, toolCalling: tool },
+ stepIndex: host.operation.stepIndex,
+ type: 'tool_start',
+ });
+
+ try {
+ const execution = await tools.run(tool, runContext);
+
+ if (execution.result.deferred) {
+ deferredTools.push(tool);
+ return;
+ }
+
+ const executionResult = execution.result;
+ const executionTime = executionResult.executionTime ?? 0;
+ const isSuccess = executionResult.success;
+
+ await host.transports.stream.publishEvent({
+ data: {
+ executionTime,
+ isSuccess,
+ attempts: execution.attempts,
+ maxAttempts: (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,
+ payload: { parentMessageId, toolCalling: tool },
+ phase: TOOL_EXECUTION_PHASE,
+ result: executionResult,
+ },
+ stepIndex: host.operation.stepIndex,
+ type: 'tool_end',
+ });
+
+ const toolMessage = await createToolMessage({
+ host,
+ parentMessageId,
+ result: executionResult,
+ state,
+ tool,
+ });
+ toolMessageIds.push(toolMessage.id);
+
+ const resultEntry: ToolResultEntry = {
+ data: executionResult,
+ executionTime,
+ isSuccess,
+ toolCall: tool,
+ toolCallId: tool.id,
+ };
+
+ events.push({ id: tool.id, result: executionResult, type: 'tool_result' });
+
+ const toolCost = tools.getCost?.(runContext.toolName) ?? 0;
+ resultEntry.usageParams = {
+ executionTime,
+ success: isSuccess,
+ toolCost,
+ toolName: runContext.toolName,
+ };
+ toolResults.push(resultEntry);
+ } catch (error) {
+ if (isPersistFatal(error)) throw error;
+
+ await tools.handleError?.(tool, error, runContext);
+ await publishError(host, error, TOOL_EXECUTION_PHASE);
+
+ events.push({ error, type: 'error' });
+ }
+ }),
+ );
+
+ const newState = structuredClone(state);
+ for (const result of toolResults) {
+ if (!result.usageParams) continue;
+
+ const { usage, cost } = UsageCounter.accumulateTool({
+ ...result.usageParams,
+ cost: newState.cost,
+ usage: newState.usage,
+ });
+ newState.usage = usage;
+ if (cost) newState.cost = cost;
+ }
+
+ persistActivatedTools({
+ effectiveManifestMap: buildEffectiveManifestMap(state),
+ newState,
+ results: toolResults,
+ stepCount: state.stepCount,
+ });
+
+ newState.messages = await host.transports.messages.query(
+ {
+ agentId: state.metadata?.agentId,
+ groupId: state.metadata?.groupId,
+ threadId: state.metadata?.threadId,
+ topicId: state.metadata?.topicId,
+ },
+ { flatten: true, resolveAssetUrls: true },
+ );
+ newState.lastModified = nowIso();
+
+ const pendingTools = [...deferredTools, ...clientTools];
+ if (pendingTools.length > 0) {
+ const pauseReason = deferredTools.length > 0 ? 'async_tool' : 'client_tool_execution';
+
+ const paused = await pauseForTools({
+ host,
+ reason: pauseReason,
+ state: newState,
+ toolsCalling: pendingTools,
+ });
+
+ return {
+ events: [...events, ...paused.events],
+ newState: paused.newState,
+ };
+ }
+
+ return {
+ events,
+ newState,
+ nextContext: {
+ payload: {
+ parentMessageId: toolMessageIds.at(-1) ?? parentMessageId,
+ toolCount: toolsCalling.length,
+ toolResults,
+ },
+ phase: 'tools_batch_result',
+ session: {
+ eventCount: events.length,
+ messageCount: newState.messages.length,
+ sessionId: host.operation.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ },
+ };
+ };
diff --git a/packages/agent-runtime/src/transport/message.ts b/packages/agent-runtime/src/transport/message.ts
index bf69f497df3..7d06a3b42c8 100644
--- a/packages/agent-runtime/src/transport/message.ts
+++ b/packages/agent-runtime/src/transport/message.ts
@@ -15,6 +15,17 @@ export interface QueryMessagesInput {
topicId?: string;
}
+export interface QueryMessagesOptions {
+ /**
+ * Return the flattened conversation-flow list. Server adapters can implement
+ * this with `@lobechat/conversation-flow`; package executors stay unaware of
+ * that dependency.
+ */
+ flatten?: boolean;
+ /** Resolve file-backed fields to external URLs before the next LLM call. */
+ resolveAssetUrls?: boolean;
+}
+
export interface UpdateToolMessageInput {
content?: string;
metadata?: Record<string, any>;
@@ -40,7 +51,7 @@ export interface MessageTransport {
deleteMessage: (id: string) => Promise<void>;
/** Existence / parent preflight; returns the id when present. */
findById: (id: string) => Promise<RuntimeMessageRef | undefined>;
- query: (params?: QueryMessagesInput) => Promise<UIChatMessage[]>;
+ query: (params?: QueryMessagesInput, options?: QueryMessagesOptions) => Promise<UIChatMessage[]>;
update: (id: string, params: Partial<UpdateMessageParams>) => Promise<void>;
updatePluginState: (id: string, state: Record<string, any>) => Promise<void>;
updateToolMessage: (id: string, params: UpdateToolMessageInput) => Promise<void>;
diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.ts
index 86501d685ef..b7a0bd9aa55 100644
--- a/packages/agent-runtime/src/transport/tool.ts
+++ b/packages/agent-runtime/src/transport/tool.ts
@@ -1,5 +1,8 @@
import type { ChatToolPayload } from '@lobechat/types';
+import type { AgentState } from '../types';
+import type { RuntimeRetryKind } from '../utils';
+
/** Neutral mirror of the server `ToolExecutionResultResponse`. */
export interface ToolRunResult {
content: string;
@@ -11,6 +14,12 @@ export interface ToolRunResult {
success: boolean;
}
+export interface ToolRunExecution {
+ attempts: number;
+ mocked?: boolean;
+ result: ToolRunResult;
+}
+
/**
* Per-call context the runtime knows at the moment of a tool call. The heavy
* server context (tool manifest map, sub-agent / group-member runners, DB
@@ -18,13 +27,26 @@ export interface ToolRunResult {
* adapter is constructed β€” NOT passed here β€” so this stays transport-neutral.
*/
export interface ToolRunContext {
+ activatedSkills?: unknown[];
activeDeviceId?: string;
agentId?: string;
assistantMessageId?: string;
+ callIndex: number;
+ effectiveManifestMap: Record<string, any>;
groupId?: string;
messageId?: string;
+ mode: 'batch' | 'single';
+ operationId: string;
+ parentMessageId: string;
+ parsedArgs: Record<string, unknown>;
+ state: AgentState;
+ stepIndex: number;
threadId?: string;
+ toolName: string;
+ toolResultMaxLength?: number;
+ toolSource?: string;
topicId?: string;
+ workspaceId?: string;
}
/**
@@ -33,5 +55,13 @@ export interface ToolRunContext {
* client adapter wraps `internal_invokeDifferentTypePlugin`.
*/
export interface ToolTransport {
- run: (call: ChatToolPayload, context: ToolRunContext) => Promise<ToolRunResult>;
+ getCost?: (toolName: string) => number;
+ handleError?: (
+ call: ChatToolPayload,
+ error: unknown,
+ context: ToolRunContext,
+ ) => Promise<void> | void;
+ maxRetries?: number;
+ run: (call: ChatToolPayload, context: ToolRunContext) => Promise<ToolRunExecution>;
+ shouldRetry?: (kind: RuntimeRetryKind, attempt: number, maxRetries: number) => boolean;
}