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(agent): converge client tool execution (#17112)

Arvin Xu1d26b5219282
diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.ts
index d207260f47b..cd117b473a1 100644
--- a/packages/agent-runtime/src/executors/tool.test.ts
+++ b/packages/agent-runtime/src/executors/tool.test.ts
@@ -174,6 +174,100 @@ describe('tool executors', () => {
);
});
+ it('executes client-source tools when the transport supports local execution', async () => {
+ host.transports.tools!.canRunClientTools = true;
+ 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).toHaveBeenCalledOnce();
+ expect(result.newState.status).toBe('running');
+ expect(result.nextContext?.phase).toBe('tool_result');
+ });
+
+ it('uses a tool message already persisted by the transport', async () => {
+ runTool.mockResolvedValueOnce({
+ attempts: 1,
+ result: { content: 'Client result', executionTime: 10, success: true },
+ resultPersisted: true,
+ toolMessageId: 'client-tool-msg',
+ });
+ 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(createToolMessage).not.toHaveBeenCalled();
+ expect(query).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ groupId: undefined,
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+ expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'client-tool-msg' });
+ });
+
+ it('does not advance after the transport reports cancellation', async () => {
+ runTool.mockResolvedValueOnce({
+ attempts: 0,
+ interrupted: true,
+ result: { content: 'Cancelled', success: false },
+ resultPersisted: true,
+ toolMessageId: 'cancelled-tool-msg',
+ });
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },
+ type: 'call_tool',
+ };
+ const state = createState();
+
+ const result = await callTool(host)(instruction, state);
+
+ expect(result).toEqual({ events: [], newState: state });
+ expect(createToolMessage).not.toHaveBeenCalled();
+ });
+
+ it('returns client sub-agent stop states to the agent but terminates other stop results', async () => {
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },
+ type: 'call_tool',
+ };
+
+ runTool.mockResolvedValueOnce({
+ attempts: 1,
+ result: {
+ content: 'Dispatch client sub-agent',
+ state: { type: 'execClientSubAgent' },
+ stop: true,
+ 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');
+ expect(stopped.nextContext).toBeUndefined();
+ });
+
it('executes server tools in a mixed batch then parks for client tools', async () => {
const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {
payload: {
@@ -211,6 +305,32 @@ describe('tool executors', () => {
);
});
+ it('uses tool messages already persisted by the transport in a batch', async () => {
+ host.transports.tools!.canRunClientTools = true;
+ runTool.mockResolvedValueOnce({
+ attempts: 1,
+ result: { content: 'Client result', executionTime: 10, success: true },
+ resultPersisted: true,
+ toolMessageId: 'client-tool-msg',
+ });
+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolsCalling: [createToolCall('client-call', 'client-tool')],
+ },
+ type: 'call_tools_batch',
+ };
+
+ const result = await callToolsBatch(host)(
+ instruction,
+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),
+ );
+
+ expect(createToolMessage).not.toHaveBeenCalled();
+ expect(host.transports.messages.updateToolMessage).not.toHaveBeenCalled();
+ expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'client-tool-msg' });
+ });
+
it('publishes and rethrows tool-message persist errors', async () => {
const error = new Error('database failed');
createToolMessage.mockRejectedValueOnce(error);
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index 1f9e27d7fbb..a5df21801ad 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -2,7 +2,13 @@ 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 type {
+ AgentEvent,
+ AgentInstruction,
+ AgentRuntimeContext,
+ AgentState,
+ InstructionExecutor,
+} from '../types';
import { extractActivatedSkillsFromMessages } from '../utils';
const TOOL_EXECUTION_PHASE = 'tool_execution';
@@ -107,13 +113,17 @@ const createRunContext = ({
host,
mode,
parentMessageId,
+ reuseExistingMessage,
state,
+ stepContext,
tool,
}: {
host: AgentRuntimeHost;
mode: ToolRunContext['mode'];
parentMessageId: string;
+ reuseExistingMessage?: boolean;
state: AgentState;
+ stepContext?: AgentRuntimeContext['stepContext'];
tool: ChatToolPayload;
}): ToolRunContext => {
const toolName = toolNameOf(tool);
@@ -123,19 +133,21 @@ const createRunContext = ({
return {
activatedSkills: extractActivatedSkillsFromMessages(state.messages),
- agentId: state.metadata?.agentId,
+ agentId: host.operation.agentId ?? state.metadata?.agentId,
assistantMessageId: parentMessageId,
callIndex: resolveCallIndex(state, toolName),
effectiveManifestMap: buildEffectiveManifestMap(state),
- groupId: state.metadata?.groupId,
+ groupId: host.operation.groupId ?? state.metadata?.groupId,
messageId: state.metadata?.sourceMessageId,
mode,
operationId: host.operation.operationId,
parentMessageId,
parsedArgs: parseToolArgs(tool),
+ reuseExistingMessage,
state,
stepIndex: host.operation.stepIndex,
- threadId: state.metadata?.threadId,
+ stepContext,
+ threadId: host.operation.threadId ?? state.metadata?.threadId,
toolName,
toolResultMaxLength: agentConfig?.chatConfig?.toolResultMaxLength,
toolSource,
@@ -221,19 +233,26 @@ const createToolMessage = async ({
tool: ChatToolPayload;
}) => {
try {
+ const agentId = host.operation.agentId ?? state.metadata?.agentId;
+ if (!agentId) {
+ throw new Error(
+ `[call_tool] Missing agentId for tool message (op=${host.operation.operationId})`,
+ );
+ }
+
return await host.transports.messages.createToolMessage({
- agentId: state.metadata!.agentId!,
+ agentId,
content: result.content,
- groupId: state.metadata?.groupId ?? undefined,
+ groupId: host.operation.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,
+ threadId: host.operation.threadId ?? state.metadata?.threadId,
tool_call_id: tool.id,
- topicId: state.metadata?.topicId,
+ topicId: host.operation.topicId ?? state.metadata?.topicId,
});
} catch (error) {
await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);
@@ -300,7 +319,7 @@ const persistActivatedTools = ({
export const callTool =
(host: AgentRuntimeHost): InstructionExecutor =>
- async (instruction, state) => {
+ async (instruction, state, runtimeContext) => {
const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tool' }>;
const tools = requireToolTransport(host);
const tool = payload.toolCalling;
@@ -309,7 +328,9 @@ export const callTool =
host,
mode: 'single',
parentMessageId: payload.parentMessageId,
+ reuseExistingMessage: payload.skipCreateToolMessage,
state,
+ stepContext: runtimeContext?.stepContext,
tool,
});
@@ -319,7 +340,7 @@ export const callTool =
type: 'tool_start',
});
- if (runContext.toolSource === 'client') {
+ if (runContext.toolSource === 'client' && !tools.canRunClientTools) {
return pauseForTools({
host,
instruction,
@@ -332,6 +353,10 @@ export const callTool =
try {
const execution = await tools.run(tool, runContext);
+ if (execution.interrupted) {
+ return { events, newState: state };
+ }
+
if (execution.result.deferred) {
return pauseForTools({
host,
@@ -360,7 +385,12 @@ export const callTool =
});
let toolMessageId: string;
- if (payload.skipCreateToolMessage) {
+ if (execution.toolMessageId) {
+ toolMessageId = execution.toolMessageId;
+ if (!execution.resultPersisted) {
+ await updateExistingToolMessage({ host, result: executionResult, toolMessageId });
+ }
+ } else if (payload.skipCreateToolMessage) {
toolMessageId = payload.parentMessageId;
await updateExistingToolMessage({ host, result: executionResult, toolMessageId });
} else {
@@ -375,13 +405,22 @@ export const callTool =
}
const newState = structuredClone(state);
- newState.messages.push({
- content: executionResult.content,
- plugin: tool,
- pluginState: executionResult.state,
- role: 'tool',
- tool_call_id: tool.id,
- });
+ if (execution.resultPersisted) {
+ newState.messages = await host.transports.messages.query({
+ agentId: runContext.agentId,
+ groupId: runContext.groupId,
+ threadId: runContext.threadId,
+ topicId: runContext.topicId,
+ });
+ } else {
+ 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' });
@@ -417,7 +456,14 @@ export const callTool =
const legacyAgentInvocationStateType = executionResult.state?.type as string | undefined;
const isLegacyAgentInvocationState =
legacyAgentInvocationStateType === 'execSubAgent' ||
- legacyAgentInvocationStateType === 'execSubAgents';
+ legacyAgentInvocationStateType === 'execSubAgents' ||
+ legacyAgentInvocationStateType === 'execClientSubAgent' ||
+ legacyAgentInvocationStateType === 'execClientSubAgents';
+
+ if (executionResult.stop && !isLegacyAgentInvocationState) {
+ newState.status = 'done';
+ return { events, newState };
+ }
return {
events,
@@ -475,7 +521,8 @@ export const callToolsBatch =
const serverTools: ChatToolPayload[] = [];
for (const tool of toolsCalling) {
- if (resolveToolSource(state, tool) === 'client') clientTools.push(tool);
+ if (resolveToolSource(state, tool) === 'client' && !tools.canRunClientTools)
+ clientTools.push(tool);
else serverTools.push(tool);
}
@@ -529,14 +576,23 @@ export const callToolsBatch =
type: 'tool_end',
});
- const toolMessage = await createToolMessage({
- host,
- parentMessageId,
- result: executionResult,
- state,
- tool,
- });
- toolMessageIds.push(toolMessage.id);
+ let toolMessageId: string;
+ if (execution.toolMessageId) {
+ toolMessageId = execution.toolMessageId;
+ if (!execution.resultPersisted) {
+ await updateExistingToolMessage({ host, result: executionResult, toolMessageId });
+ }
+ } else {
+ const toolMessage = await createToolMessage({
+ host,
+ parentMessageId,
+ result: executionResult,
+ state,
+ tool,
+ });
+ toolMessageId = toolMessage.id;
+ }
+ toolMessageIds.push(toolMessageId);
const resultEntry: ToolResultEntry = {
data: executionResult,
diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.ts
index b7a0bd9aa55..94bc2737bd6 100644
--- a/packages/agent-runtime/src/transport/tool.ts
+++ b/packages/agent-runtime/src/transport/tool.ts
@@ -1,4 +1,4 @@
-import type { ChatToolPayload } from '@lobechat/types';
+import type { ChatToolPayload, RuntimeStepContext } from '@lobechat/types';
import type { AgentState } from '../types';
import type { RuntimeRetryKind } from '../utils';
@@ -11,13 +11,21 @@ export interface ToolRunResult {
error?: unknown;
executionTime?: number;
state?: Record<string, any>;
+ /** Tool result requests the current runtime flow to stop. */
+ stop?: boolean;
success: boolean;
}
export interface ToolRunExecution {
attempts: number;
+ /** Execution was cancelled after the client created its optimistic message. */
+ interrupted?: boolean;
mocked?: boolean;
result: ToolRunResult;
+ /** The transport already persisted the result into its tool message. */
+ resultPersisted?: boolean;
+ /** Existing/pre-created tool message owned by the transport. */
+ toolMessageId?: string;
}
/**
@@ -39,7 +47,10 @@ export interface ToolRunContext {
operationId: string;
parentMessageId: string;
parsedArgs: Record<string, unknown>;
+ /** Reuse the parent tool message when resuming after intervention. */
+ reuseExistingMessage?: boolean;
state: AgentState;
+ stepContext?: RuntimeStepContext;
stepIndex: number;
threadId?: string;
toolName: string;
@@ -55,6 +66,8 @@ export interface ToolRunContext {
* client adapter wraps `internal_invokeDifferentTypePlugin`.
*/
export interface ToolTransport {
+ /** This runtime can execute tools whose source is the client directly. */
+ canRunClientTools?: boolean;
getCost?: (toolName: string) => number;
handleError?: (
call: ChatToolPayload,
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts
index 46d8eee6146..17245d896bb 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts
@@ -135,7 +135,12 @@ describe('call_tool executor', () => {
expect(result.events).toHaveLength(1);
expect(result.events[0].type).toBe('tool_result');
const toolResultEvent = result.events[0] as any;
- expect(toolResultEvent.result).toEqual({ data: 'search results', error: null });
+ expect(toolResultEvent.result).toMatchObject({
+ data: 'search results',
+ error: null,
+ success: true,
+ });
+ expect(toolResultEvent.result.content).toContain('search results');
});
});
@@ -322,7 +327,7 @@ describe('call_tool executor', () => {
const state = createInitialState();
// When
- const result = await executeWithMockContext({
+ await executeWithMockContext({
executor: 'call_tool',
instruction,
state,
@@ -702,7 +707,7 @@ describe('call_tool executor', () => {
});
// When
- const result = await executeWithMockContext({
+ await executeWithMockContext({
executor: 'call_tool',
instruction,
state,
@@ -1366,7 +1371,7 @@ describe('call_tool executor', () => {
expect(result.newState.operationId).toBe('preserve-session');
expect(result.newState.stepCount).toBe(15);
expect(result.newState.status).toBe('running');
- expect(result.newState.lastModified).toBe('2024-01-01T00:00:00.000Z');
+ expect(result.newState.lastModified).not.toBe('2024-01-01T00:00:00.000Z');
});
it('should not mutate original state', async () => {
@@ -1379,7 +1384,7 @@ describe('call_tool executor', () => {
const instruction = createCallToolInstruction();
const state = createInitialState({ operationId: 'immutable-test', stepCount: 5 });
- const originalState = JSON.parse(JSON.stringify(state));
+ const originalState = structuredClone(state);
// When
await executeWithMockContext({
@@ -1589,7 +1594,7 @@ describe('call_tool executor', () => {
const state = createInitialState();
// When
- const result = await executeWithMockContext({
+ await executeWithMockContext({
executor: 'call_tool',
instruction,
state,
@@ -1664,7 +1669,7 @@ describe('call_tool executor', () => {
const state = createInitialState();
// When
- const result = await executeWithMockContext({
+ await executeWithMockContext({
executor: 'call_tool',
instruction,
state,
@@ -1898,8 +1903,7 @@ describe('call_tool executor', () => {
// Track cancel handler registration
let executeToolCancelHandler:
- | ((context: OperationCancelContext) => void | Promise<void>)
- | undefined;
+ ((context: OperationCancelContext) => void | Promise<void>) | undefined;
const originalOnOperationCancel = mockStore.onOperationCancel;
mockStore.onOperationCancel = vi.fn(
(opId: string, handler: (context: OperationCancelContext) => void | Promise<void>) => {
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 81071948d3a..19c2a1ab2b0 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -2,16 +2,13 @@ import type {
AgentEvent,
AgentInstruction,
AgentInstructionCallLlm,
- AgentInstructionCallTool,
AgentInstructionCompressContext,
AgentInstructionExecSubAgent,
AgentInstructionExecSubAgents,
AgentRuntimeContext,
AgentRuntimeHost,
- GeneralAgentCallingToolInstructionPayload,
GeneralAgentCallLLMInstructionPayload,
GeneralAgentCallLLMResultPayload,
- GeneralAgentCallToolResultPayload,
GeneralAgentCompressionResultPayload,
InstructionExecutor,
SubAgentResultPayload,
@@ -19,6 +16,7 @@ import type {
SubAgentTask,
} from '@lobechat/agent-runtime';
import {
+ callTool as createCallToolExecutor,
finish as createFinishExecutor,
requestHumanApprove as createRequestHumanApproveExecutor,
resolveAbortedTools as createResolveAbortedToolsExecutor,
@@ -28,8 +26,6 @@ import { countContextTokens, type ToolsEngine } from '@lobechat/context-engine';
import { chainCompressContext } from '@lobechat/prompts';
import {
type ChatMessageError,
- type ChatToolPayload,
- type CreateMessageParams,
type MessageMetadata,
type MessageToolCall,
type ModelUsage,
@@ -56,12 +52,6 @@ import { type StreamChunk } from './types/streaming';
const log = debug('lobe-store:agent-executors');
-// Tool pricing configuration (USD per call)
-const TOOL_PRICING: Record<string, number> = {
- 'lobe-web-browsing/craw': 0.002,
- 'lobe-web-browsing/search': 0.001,
-};
-
const isAbortError = (error: unknown, abortController?: AbortController) =>
!!abortController?.signal.aborted ||
(error instanceof Error &&
@@ -697,442 +687,7 @@ export const createAgentExecutors = (context: {
};
},
- /**
- * Custom call_tool executor
- * Wraps internal_invokeDifferentTypePlugin
- * Follows server-side pattern: always create tool message before execution
- */
- call_tool: async (instruction, state, runtimeContext) => {
- const payload = (instruction as AgentInstructionCallTool)
- .payload as GeneralAgentCallingToolInstructionPayload;
-
- const events: AgentEvent[] = [];
- const sessionLogId = `${state.operationId}:${state.stepCount}`;
-
- log('[%s][call_tool] Executor start, payload: %O', sessionLogId, payload);
-
- // Convert CallingToolPayload to ChatToolPayload for ToolExecutionService
- const chatToolPayload: ChatToolPayload = payload.toolCalling;
-
- const toolName = `${chatToolPayload.identifier}/${chatToolPayload.apiName}`;
- const startTime = performance.now();
-
- // Get context from operation
- const opContext = getOperationContext();
- // Get assistant message to derive the same-turn source user message when the root
- // runtime operation is anchored to the assistant message.
- const latestMessages = context.get().dbMessagesMap[context.messageKey] || [];
- const existingToolMessage = payload.skipCreateToolMessage
- ? latestMessages.find((m) => m.id === payload.parentMessageId)
- : undefined;
- const assistantMessage =
- latestMessages.find((m) => m.id === payload.parentMessageId && m.role === 'assistant') ??
- (existingToolMessage?.parentId
- ? latestMessages.find(
- (m) => m.id === existingToolMessage.parentId && m.role === 'assistant',
- )
- : undefined) ??
- (opContext.messageId
- ? latestMessages.find((m) => m.id === opContext.messageId && m.role === 'assistant')
- : undefined) ??
- latestMessages.findLast((m) => m.role === 'assistant');
- const sourceMessageId =
- opContext.sourceMessageId ??
- assistantMessage?.parentId ??
- (opContext.messageId !== assistantMessage?.id ? opContext.messageId : undefined);
-
- // ============ Create toolCalling operation (top-level) ============
- const { operationId: toolOperationId } = context.get().startOperation({
- type: 'toolCalling',
- context: {
- agentId: opContext.agentId!,
- groupId: opContext.groupId,
- scope: opContext.scope,
- sourceMessageId,
- topicId: opContext.topicId,
- threadId: opContext.threadId,
- viewedTask: opContext.viewedTask,
- },
- parentOperationId: context.operationId,
- metadata: {
- startTime: Date.now(),
- identifier: chatToolPayload.identifier,
- apiName: chatToolPayload.apiName,
- tool_call_id: chatToolPayload.id,
- },
- });
-
- try {
- let toolMessageId: string;
-
- if (payload.skipCreateToolMessage) {
- // Reuse existing tool message (resumption mode)
- toolMessageId = payload.parentMessageId;
-
- log(
- '[%s][call_tool] Resuming with existing tool message: %s (status: %s)',
- sessionLogId,
- toolMessageId,
- existingToolMessage?.pluginIntervention?.status,
- );
- } else {
- // Create new tool message (normal mode)
- log(
- '[%s][call_tool] Creating tool message for tool_call_id: %s',
- sessionLogId,
- chatToolPayload.id,
- );
-
- // ============ Sub-operation 1: Create tool message ============
- const createToolMsgOpId = context.get().startOperation({
- type: 'createToolMessage',
- context: {
- agentId: opContext.agentId!,
- topicId: opContext.topicId,
- threadId: opContext.threadId,
- },
- parentOperationId: toolOperationId,
- metadata: {
- startTime: Date.now(),
- tool_call_id: chatToolPayload.id,
- },
- }).operationId;
-
- // Register cancel handler: Ensure message creation completes, then mark as aborted
- context.get().onOperationCancel(createToolMsgOpId, async ({ metadata }) => {
- log(
- '[%s][call_tool] createToolMessage cancelled, ensuring creation completes',
- sessionLogId,
- );
-
- // Wait for message creation to complete (ensure-complete strategy)
- const createResult = await metadata?.createMessagePromise;
- if (createResult) {
- const msgId = createResult.id;
- // Update message to aborted state
- await Promise.all([
- context
- .get()
- .optimisticUpdateMessageContent(
- msgId,
- 'Tool execution was cancelled by user.',
- undefined,
- { operationId: createToolMsgOpId },
- ),
- context
- .get()
- .optimisticUpdateMessagePlugin(
- msgId,
- { intervention: { status: 'aborted' } },
- { operationId: createToolMsgOpId },
- ),
- ]);
- }
- });
-
- // Execute creation and save Promise to metadata
- // Use effective agentId (subAgentId for group orchestration)
- const effectiveAgentId = getEffectiveAgentId();
- const toolMessageParams: CreateMessageParams = {
- content: '',
- groupId: assistantMessage?.groupId,
- parentId: payload.parentMessageId,
- plugin: chatToolPayload,
- role: 'tool',
- agentId: effectiveAgentId!,
- threadId: opContext.threadId,
- tool_call_id: chatToolPayload.id,
- topicId: opContext.topicId ?? undefined,
- };
-
- const createPromise = context
- .get()
- .optimisticCreateMessage(toolMessageParams, { operationId: createToolMsgOpId });
- context.get().updateOperationMetadata(createToolMsgOpId, {
- createMessagePromise: createPromise,
- });
- const createResult = await createPromise;
-
- if (!createResult) {
- context.get().failOperation(createToolMsgOpId, {
- type: 'CreateMessageError',
- message: `Failed to create tool message for tool_call_id: ${chatToolPayload.id}`,
- });
- throw new Error(
- `Failed to create tool message for tool_call_id: ${chatToolPayload.id}`,
- );
- }
-
- toolMessageId = createResult.id;
- log('[%s][call_tool] Created tool message, id: %s', sessionLogId, toolMessageId);
- context.get().completeOperation(createToolMsgOpId);
- }
-
- // Check if parent operation was cancelled while creating message
- const toolOperation = toolOperationId
- ? context.get().operations[toolOperationId]
- : undefined;
- if (toolOperation?.abortController.signal.aborted) {
- log('[%s][call_tool] Parent operation cancelled, skipping tool execution', sessionLogId);
- // Message already created with aborted status by cancel handler
- return { events, newState: state };
- }
-
- // ============ Sub-operation 2: Execute tool call ============
- // Auto-associates message with this operation via messageId in context
- const { operationId: executeToolOpId } = context.get().startOperation({
- type: 'executeToolCall',
- context: {
- messageId: toolMessageId,
- },
- parentOperationId: toolOperationId,
- metadata: {
- startTime: Date.now(),
- tool_call_id: chatToolPayload.id,
- },
- });
-
- log(
- '[%s][call_tool] Created executeToolCall operation %s for message %s',
- sessionLogId,
- executeToolOpId,
- toolMessageId,
- );
-
- // Register cancel handler: Just update message (message already exists)
- context.get().onOperationCancel(executeToolOpId, async () => {
- log('[%s][call_tool] executeToolCall cancelled, updating message', sessionLogId);
-
- // Update message to aborted state (cleanup strategy)
- await Promise.all([
- context
- .get()
- .optimisticUpdateMessageContent(
- toolMessageId,
- 'Tool execution was cancelled by user.',
- undefined,
- { operationId: executeToolOpId },
- ),
- context
- .get()
- .optimisticUpdateMessagePlugin(
- toolMessageId,
- { intervention: { status: 'aborted' } },
- { operationId: executeToolOpId },
- ),
- ]);
- });
-
- // Execute tool - abort handling is done by cancel handler
- // Pass stepContext from runtimeContext for dynamic state access
- log(
- '[%s][call_tool] Executing tool %s (hasTodos=%s) ...',
- sessionLogId,
- toolName,
- !!runtimeContext?.stepContext?.todos,
- );
- const result: any = await context
- .get()
- .internal_invokeDifferentTypePlugin(
- toolMessageId,
- chatToolPayload,
- runtimeContext?.stepContext,
- );
-
- // Check if operation was cancelled during tool execution
- const executeToolOperation = context.get().operations[executeToolOpId];
- if (executeToolOperation?.abortController.signal.aborted) {
- log('[%s][call_tool] Tool execution completed but operation was cancelled', sessionLogId);
- // Don't complete - cancel handler already updated message to aborted
- return { events, newState: state };
- }
-
- context.get().completeOperation(executeToolOpId);
-
- const executionTime = Math.round(performance.now() - startTime);
-
- // Fallback for undefined result (e.g. tool executor not found or returned nothing)
- if (result === undefined || result === null) {
- const fallbackResult = {
- content: `Tool ${toolName} execution failed: no result returned`,
- error: { type: 'ToolExecutionError', message: 'Tool returned no result' },
- success: false,
- };
-
- if (toolOperationId) {
- context.get().failOperation(toolOperationId, {
- message: 'Tool returned no result',
- type: 'ToolExecutionError',
- });
- }
-
- events.push({ id: chatToolPayload.id, result: fallbackResult, type: 'tool_result' });
-
- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
- return { events, newState: { ...state, messages: updatedMessages } };
- }
-
- const isSuccess = result && !result.error;
-
- log(
- '[%s][call_tool] Executing %s in %dms, result: %O',
- sessionLogId,
- toolName,
- executionTime,
- result,
- );
-
- // Complete or fail the toolCalling operation
- if (toolOperationId) {
- if (isSuccess) {
- context.get().completeOperation(toolOperationId);
- } else {
- context.get().failOperation(toolOperationId, {
- type: 'ToolExecutionError',
- message: result?.error || 'Tool execution failed',
- });
- }
- }
-
- events.push({ id: chatToolPayload.id, result, type: 'tool_result' });
-
- // Get latest messages from store (already updated by internal_invokeDifferentTypePlugin)
- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
-
- const newState = { ...state, messages: updatedMessages };
-
- // Get tool unit price
- const toolCost = TOOL_PRICING[toolName] || 0;
-
- // Use UsageCounter to accumulate tool usage
- const { usage, cost } = UsageCounter.accumulateTool({
- cost: state.cost,
- executionTime,
- success: isSuccess,
- toolCost,
- toolName,
- usage: state.usage,
- });
-
- newState.usage = usage;
- if (cost) newState.cost = cost;
-
- // Find current tool statistics
- const currentToolStats = usage.tools.byTool.find((t) => t.name === toolName);
-
- // Log usage
- log(
- '[%s][tool usage] %s: calls=%d, time=%dms, success=%s, cost=$%s',
- sessionLogId,
- toolName,
- currentToolStats?.calls || 0,
- executionTime,
- isSuccess,
- toolCost.toFixed(4),
- );
-
- // Check if tool wants to stop execution flow
- if (result?.stop) {
- log('[%s][call_tool] Tool returned stop=true, state: %O', sessionLogId, result.state);
-
- const stateType = result.state?.type;
-
- // Legacy agent-invocation dispatches need to be forwarded to the Agent
- // runtime as exec_sub_agent / exec_sub_agents instructions. This covers
- // server-side callAgent task states plus the desktop client-side variants.
- const legacyAgentInvocationStateTypes = [
- 'execSubAgent',
- 'execSubAgents',
- 'execClientSubAgent',
- 'execClientSubAgents',
- ];
- if (legacyAgentInvocationStateTypes.includes(stateType)) {
- log(
- '[%s][call_tool] Detected %s state, passing to Agent for decision',
- sessionLogId,
- stateType,
- );
-
- return {
- events,
- newState,
- nextContext: {
- payload: {
- data: result,
- executionTime,
- isSuccess,
- parentMessageId: toolMessageId,
- stop: true,
- toolCall: chatToolPayload,
- toolCallId: chatToolPayload.id,
- } as GeneralAgentCallToolResultPayload,
- phase: 'tool_result',
- session: {
- eventCount: events.length,
- messageCount: newState.messages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- stepUsage: {
- cost: toolCost,
- toolName,
- unitPrice: toolCost,
- usageCount: 1,
- },
- } as AgentRuntimeContext,
- };
- }
-
- // Other stop types (speak, delegate, broadcast, etc.) - stop execution immediately
- newState.status = 'done';
-
- return {
- events,
- newState,
- nextContext: undefined,
- };
- }
-
- log('[%s][call_tool] Tool execution completed', sessionLogId);
-
- return {
- events,
- newState,
- nextContext: {
- payload: {
- data: result,
- executionTime,
- isSuccess,
- parentMessageId: toolMessageId,
- toolCall: chatToolPayload,
- toolCallId: chatToolPayload.id,
- } as GeneralAgentCallToolResultPayload,
- phase: 'tool_result',
- session: {
- eventCount: events.length,
- messageCount: newState.messages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- stepUsage: {
- cost: toolCost,
- toolName,
- unitPrice: toolCost,
- usageCount: 1,
- },
- } as AgentRuntimeContext,
- };
- } catch (error) {
- log('[%s][call_tool] ERROR: Tool execution failed: %O', sessionLogId, error);
-
- events.push({ error, type: 'error' });
-
- // Return current state on error (no state change)
- return { events, newState: state };
- }
- },
+ call_tool: usePackageExecutor(createCallToolExecutor),
finish: usePackageExecutor(createFinishExecutor),
diff --git a/src/store/chat/agents/transports/ClientToolTransport.test.ts b/src/store/chat/agents/transports/ClientToolTransport.test.ts
new file mode 100644
index 00000000000..8bc395e0d19
--- /dev/null
+++ b/src/store/chat/agents/transports/ClientToolTransport.test.ts
@@ -0,0 +1,66 @@
+import type { ToolRunContext } from '@lobechat/agent-runtime';
+import type { ChatToolPayload } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ChatStore } from '@/store/chat/store';
+
+import { ClientToolTransport } from './ClientToolTransport';
+
+describe('ClientToolTransport', () => {
+ it('preserves an explicit unsuccessful tool result without an error', async () => {
+ const completeOperation = vi.fn();
+ const failOperation = vi.fn();
+ let operationIndex = 0;
+ const store = {
+ completeOperation,
+ dbMessagesMap: {
+ 'message-key': [{ id: 'assistant-message', parentId: 'user-message', role: 'assistant' }],
+ },
+ failOperation,
+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({
+ content: 'Tool reported a handled failure',
+ success: false,
+ }),
+ onOperationCancel: vi.fn(),
+ operations: {
+ 'root-operation': {
+ context: { agentId: 'agent-1', messageId: 'assistant-message' },
+ },
+ },
+ optimisticCreateMessage: vi.fn().mockResolvedValue({ id: 'tool-message' }),
+ startOperation: vi.fn(() => ({ operationId: `child-operation-${++operationIndex}` })),
+ updateOperationMetadata: vi.fn(),
+ } as unknown as ChatStore;
+ const transport = new ClientToolTransport(() => store, 'message-key', 'root-operation');
+ const call: ChatToolPayload = {
+ apiName: 'run',
+ arguments: '{}',
+ id: 'tool-call',
+ identifier: 'client-tool',
+ type: 'default',
+ };
+ const context = {
+ callIndex: 1,
+ effectiveManifestMap: {},
+ mode: 'single',
+ operationId: 'root-operation',
+ parentMessageId: 'assistant-message',
+ parsedArgs: {},
+ state: {},
+ stepIndex: 0,
+ toolName: 'client-tool/run',
+ } as ToolRunContext;
+
+ const execution = await transport.run(call, context);
+
+ expect(execution.result).toMatchObject({
+ content: 'Tool reported a handled failure',
+ success: false,
+ });
+ expect(failOperation).toHaveBeenCalledWith('child-operation-1', {
+ message: 'Tool execution failed',
+ type: 'ToolExecutionError',
+ });
+ expect(completeOperation).not.toHaveBeenCalledWith('child-operation-1');
+ });
+});
diff --git a/src/store/chat/agents/transports/ClientToolTransport.ts b/src/store/chat/agents/transports/ClientToolTransport.ts
new file mode 100644
index 00000000000..192ca5bbe73
--- /dev/null
+++ b/src/store/chat/agents/transports/ClientToolTransport.ts
@@ -0,0 +1,261 @@
+import type {
+ ToolRunContext,
+ ToolRunExecution,
+ ToolRunResult,
+ ToolTransport,
+} from '@lobechat/agent-runtime';
+import type { ChatToolPayload, CreateMessageParams } from '@lobechat/types';
+
+import type { ChatStore } from '@/store/chat/store';
+
+const TOOL_PRICING: Record<string, number> = {
+ 'lobe-web-browsing/craw': 0.002,
+ 'lobe-web-browsing/search': 0.001,
+};
+
+const CANCELLED_CONTENT = 'Tool execution was cancelled by user.';
+
+/** Client tool adapter backed by optimistic messages and local tool executors. */
+export class ClientToolTransport implements ToolTransport {
+ canRunClientTools = true;
+ maxRetries = 0;
+
+ constructor(
+ private readonly get: () => ChatStore,
+ private readonly messageKey: string,
+ private readonly operationId: string,
+ ) {}
+
+ getCost(toolName: string) {
+ return TOOL_PRICING[toolName] ?? 0;
+ }
+
+ async run(call: ChatToolPayload, context: ToolRunContext): Promise<ToolRunExecution> {
+ const store = this.get();
+ const rootOperation = store.operations[this.operationId];
+ if (!rootOperation) throw new Error(`Operation not found: ${this.operationId}`);
+
+ const opContext = rootOperation.context;
+ const messages = store.dbMessagesMap[this.messageKey] ?? [];
+ const existingToolMessage = context.reuseExistingMessage
+ ? messages.find((message) => message.id === context.parentMessageId)
+ : undefined;
+ const assistantMessage =
+ messages.find(
+ (message) => message.id === context.parentMessageId && message.role === 'assistant',
+ ) ??
+ (existingToolMessage?.parentId
+ ? messages.find(
+ (message) =>
+ message.id === existingToolMessage.parentId && message.role === 'assistant',
+ )
+ : undefined) ??
+ (opContext.messageId
+ ? messages.find(
+ (message) => message.id === opContext.messageId && message.role === 'assistant',
+ )
+ : undefined) ??
+ messages.findLast((message) => message.role === 'assistant');
+ const sourceMessageId =
+ opContext.sourceMessageId ??
+ assistantMessage?.parentId ??
+ (opContext.messageId !== assistantMessage?.id ? opContext.messageId : undefined);
+ const effectiveAgentId =
+ opContext.subAgentId && opContext.scope !== 'sub_agent'
+ ? opContext.subAgentId
+ : opContext.agentId;
+
+ const { operationId: toolOperationId } = store.startOperation({
+ context: {
+ agentId: opContext.agentId!,
+ groupId: opContext.groupId,
+ scope: opContext.scope,
+ sourceMessageId,
+ threadId: opContext.threadId,
+ topicId: opContext.topicId,
+ viewedTask: opContext.viewedTask,
+ },
+ metadata: {
+ apiName: call.apiName,
+ identifier: call.identifier,
+ startTime: Date.now(),
+ tool_call_id: call.id,
+ },
+ parentOperationId: this.operationId,
+ type: 'toolCalling',
+ });
+
+ try {
+ const toolMessageId = context.reuseExistingMessage
+ ? context.parentMessageId
+ : await this.createToolMessage({
+ assistantGroupId: assistantMessage?.groupId ?? undefined,
+ call,
+ effectiveAgentId,
+ parentMessageId: context.parentMessageId,
+ toolOperationId,
+ });
+
+ if (store.operations[toolOperationId]?.abortController.signal.aborted) {
+ return this.createInterruptedExecution(toolMessageId);
+ }
+
+ const { operationId: executeOperationId } = store.startOperation({
+ context: { messageId: toolMessageId },
+ metadata: { startTime: Date.now(), tool_call_id: call.id },
+ parentOperationId: toolOperationId,
+ type: 'executeToolCall',
+ });
+
+ store.onOperationCancel(executeOperationId, async () => {
+ await this.markMessageCancelled(toolMessageId, executeOperationId);
+ });
+
+ const startedAt = performance.now();
+ const rawResult = await store.internal_invokeDifferentTypePlugin(
+ toolMessageId,
+ call,
+ context.stepContext,
+ );
+
+ if (store.operations[executeOperationId]?.abortController.signal.aborted) {
+ return this.createInterruptedExecution(toolMessageId);
+ }
+
+ store.completeOperation(executeOperationId);
+
+ const executionTime = Math.round(performance.now() - startedAt);
+ const result = this.normalizeResult(rawResult, context.toolName, executionTime);
+
+ if (result.success) {
+ store.completeOperation(toolOperationId);
+ } else {
+ store.failOperation(toolOperationId, {
+ message: this.errorMessage(result.error),
+ type: 'ToolExecutionError',
+ });
+ }
+
+ return {
+ attempts: 1,
+ result,
+ resultPersisted: rawResult !== undefined && rawResult !== null,
+ toolMessageId,
+ };
+ } catch (error) {
+ store.failOperation(toolOperationId, {
+ message: this.errorMessage(error),
+ type: 'ToolExecutionError',
+ });
+ throw error;
+ }
+ }
+
+ private async createToolMessage(input: {
+ assistantGroupId?: string;
+ call: ChatToolPayload;
+ effectiveAgentId?: string | null;
+ parentMessageId: string;
+ toolOperationId: string;
+ }): Promise<string> {
+ const store = this.get();
+ const rootContext = store.operations[this.operationId]!.context;
+ const { operationId: createOperationId } = store.startOperation({
+ context: {
+ agentId: rootContext.agentId!,
+ threadId: rootContext.threadId,
+ topicId: rootContext.topicId,
+ },
+ metadata: { startTime: Date.now(), tool_call_id: input.call.id },
+ parentOperationId: input.toolOperationId,
+ type: 'createToolMessage',
+ });
+
+ store.onOperationCancel(createOperationId, async ({ metadata }) => {
+ const createResult = await metadata?.createMessagePromise;
+ if (createResult) await this.markMessageCancelled(createResult.id, createOperationId);
+ });
+
+ const params: CreateMessageParams = {
+ agentId: input.effectiveAgentId!,
+ content: '',
+ groupId: input.assistantGroupId,
+ parentId: input.parentMessageId,
+ plugin: input.call,
+ role: 'tool',
+ threadId: rootContext.threadId,
+ tool_call_id: input.call.id,
+ topicId: rootContext.topicId ?? undefined,
+ };
+ const createPromise = store.optimisticCreateMessage(params, {
+ operationId: createOperationId,
+ });
+ store.updateOperationMetadata(createOperationId, { createMessagePromise: createPromise });
+
+ const createResult = await createPromise;
+ if (!createResult) {
+ const error = {
+ message: `Failed to create tool message for tool_call_id: ${input.call.id}`,
+ type: 'CreateMessageError',
+ };
+ store.failOperation(createOperationId, error);
+ throw new Error(error.message);
+ }
+
+ store.completeOperation(createOperationId);
+ return createResult.id;
+ }
+
+ private createInterruptedExecution(toolMessageId: string): ToolRunExecution {
+ return {
+ attempts: 0,
+ interrupted: true,
+ result: { content: CANCELLED_CONTENT, success: false },
+ resultPersisted: true,
+ toolMessageId,
+ };
+ }
+
+ private errorMessage(error: unknown): string {
+ if (error instanceof Error) return error.message;
+ if (typeof error === 'string') return error;
+ if (error && typeof error === 'object') {
+ const message = (error as { message?: unknown }).message;
+ if (typeof message === 'string') return message;
+ }
+ return 'Tool execution failed';
+ }
+
+ private async markMessageCancelled(messageId: string, operationId: string) {
+ const store = this.get();
+ await Promise.all([
+ store.optimisticUpdateMessageContent(messageId, CANCELLED_CONTENT, undefined, {
+ operationId,
+ }),
+ store.optimisticUpdateMessagePlugin(
+ messageId,
+ { intervention: { status: 'aborted' } },
+ { operationId },
+ ),
+ ]);
+ }
+
+ private normalizeResult(rawResult: any, toolName: string, executionTime: number): ToolRunResult {
+ if (rawResult === undefined || rawResult === null) {
+ return {
+ content: `Tool ${toolName} execution failed: no result returned`,
+ error: { message: 'Tool returned no result', type: 'ToolExecutionError' },
+ executionTime,
+ success: false,
+ };
+ }
+
+ return {
+ ...rawResult,
+ content:
+ typeof rawResult.content === 'string' ? rawResult.content : JSON.stringify(rawResult),
+ executionTime,
+ success: typeof rawResult.success === 'boolean' ? rawResult.success : !rawResult.error,
+ };
+ }
+}
diff --git a/src/store/chat/agents/transports/buildClientRuntimeHost.ts b/src/store/chat/agents/transports/buildClientRuntimeHost.ts
index 61c6d28ff3e..184e77e8ec1 100644
--- a/src/store/chat/agents/transports/buildClientRuntimeHost.ts
+++ b/src/store/chat/agents/transports/buildClientRuntimeHost.ts
@@ -3,6 +3,7 @@ import type { AgentRuntimeHost, OperationStore, StreamSink } from '@lobechat/age
import type { ChatStore } from '@/store/chat/store';
import { ClientMessageTransport } from './ClientMessageTransport';
+import { ClientToolTransport } from './ClientToolTransport';
const localOperationStore: OperationStore = {
clearRunningMark: async () => {},
@@ -40,6 +41,7 @@ export const buildClientRuntimeHost = (context: {
messages: new ClientMessageTransport(context.get, context.messageKey, context.operationId),
operationStore: localOperationStore,
stream: localStreamSink,
+ tools: new ClientToolTransport(context.get, context.messageKey, context.operationId),
},
};
};