π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat: support client-side function tool execution in Response API (#13414)
Arvin Xu674c84925454
diff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.tsindex 8c27225e43a..2ea5e9c6c55 100644--- a/packages/context-engine/src/engine/tools/types.ts+++ b/packages/context-engine/src/engine/tools/types.ts@@ -160,7 +160,7 @@ export interface UniformTool {// ---- Tool Lifecycle Types -----export type ToolSource = 'builtin' | 'plugin' | 'mcp' | 'klavis' | 'lobehubSkill';+export type ToolSource = 'builtin' | 'client' | 'plugin' | 'mcp' | 'klavis' | 'lobehubSkill';/*** How a tool was activated at step leveldiff --git a/packages/openapi/src/services/responses.service.ts b/packages/openapi/src/services/responses.service.tsindex b5e130cfd0d..153c612badf 100644--- a/packages/openapi/src/services/responses.service.ts+++ b/packages/openapi/src/services/responses.service.ts@@ -11,6 +11,7 @@ import { AiAgentService } from '@/server/services/aiAgent';import { BaseService } from '../common/base.service';import type {CreateResponseRequest,+ FunctionCallOutputItem,InputItem,OutputItem,ResponseObject,@@ -36,6 +37,49 @@ export class ResponsesService extends BaseService {return tools.filter((t) => t.type !== 'function').map((t) => t.type);}+ /**+ * Extract function tool definitions from tools array+ */+ private extractFunctionTools(+ tools?: Tool[] | null,+ ): Array<{ description?: string; name: string; parameters?: Record<string, any> }> {+ if (!tools) return [];+ return tools+ .filter((t): t is Tool & { type: 'function' } => t.type === 'function')+ .map((t) => ({+ description: (t as any).description,+ name: (t as any).name,+ parameters: (t as any).parameters,+ }));+ }++ /**+ * Check if input contains function_call_output items (resume flow)+ */+ private hasFunctionCallOutputs(input: string | InputItem[]): boolean {+ if (typeof input === 'string') return false;+ return input.some((item) => item.type === 'function_call_output');+ }++ /**+ * Extract function_call_output items from input+ */+ private extractFunctionCallOutputs(input: string | InputItem[]): FunctionCallOutputItem[] {+ if (typeof input === 'string') return [];+ return input.filter(+ (item): item is FunctionCallOutputItem => item.type === 'function_call_output',+ );+ }++ /**+ * Build a prompt from function_call_output items for the resume flow.+ * Encodes tool results so the LLM can continue the conversation.+ */+ private buildToolResultPrompt(outputs: FunctionCallOutputItem[]): string {+ const parts = outputs.map((o) => `Tool call ${o.call_id} returned: ${o.output}`);+ return parts.join('\n');+ }+/*** Extract a prompt string from OpenResponses input*/@@ -139,11 +183,16 @@ export class ResponsesService extends BaseService {// Handle tool_calls from assistantif (hasToolCalls) {for (const toolCall of msg.tool_calls) {+ // Convert internal tool names: lobe-client-fn____get_weather β get_weather+ let fnName = toolCall.function?.name ?? '';+ if (fnName.startsWith('lobe-client-fn____')) {+ fnName = fnName.slice('lobe-client-fn____'.length);+ }output.push({arguments: toolCall.function?.arguments ?? '{}',call_id: toolCall.id ?? `call_${itemCounter}`,id: `fc_${responseId}_${itemCounter++}`,- name: toolCall.function?.name ?? '',+ name: fnName,status: 'completed' as const,type: 'function_call' as const,});@@ -201,7 +250,6 @@ export class ResponsesService extends BaseService {try {const model = params.model;- const prompt = this.extractPrompt(params.input);const instructions = this.buildInstructions(params);// Resolve topicId from previous_response_id for multi-turn@@ -209,8 +257,17 @@ export class ResponsesService extends BaseService {? this.extractTopicIdFromResponseId(params.previous_response_id): null;+ // Check for function_call_output resume flow+ const functionCallOutputs = this.extractFunctionCallOutputs(params.input);+ const isResumeFlow = functionCallOutputs.length > 0 && previousTopicId;++ const prompt = isResumeFlow+ ? this.buildToolResultPrompt(functionCallOutputs)+ : this.extractPrompt(params.input);+this.log('info', 'Creating response via execAgent', {hasInstructions: !!instructions,+ isResumeFlow,model,previousTopicId,prompt: prompt.slice(0, 50),@@ -219,12 +276,14 @@ export class ResponsesService extends BaseService {// 1. Create agent operation without auto-start// model field is used as agentIdconst additionalPluginIds = this.extractHostedToolIds(params.tools);+ const functionTools = this.extractFunctionTools(params.tools);const aiAgentService = new AiAgentService(this.db, this.userId);const execResult = await aiAgentService.execAgent({additionalPluginIds: additionalPluginIds.length > 0 ? additionalPluginIds : undefined,agentId: model,appContext: previousTopicId ? { topicId: previousTopicId } : undefined,autoStart: false,+ functionTools: functionTools.length > 0 ? functionTools : undefined,instructions,prompt,stream: false,@@ -247,14 +306,23 @@ export class ResponsesService extends BaseService {const { output, outputText } = this.extractOutputItems(finalState, responseId);const usage = this.extractUsage(finalState);+ const isClientToolInterrupt =+ finalState.status === 'interrupted' &&+ finalState.interruption?.reason === 'client_tool_execution';+return this.buildResponseObject({- completedAt: Math.floor(Date.now() / 1000),+ completedAt: isClientToolInterrupt ? null : Math.floor(Date.now() / 1000),createdAt,id: responseId,+ incompleteDetails: isClientToolInterrupt ? { reason: 'client_tool_execution' } : undefined,output,outputText,params,- status: finalState.status === 'error' ? 'failed' : 'completed',+ status: isClientToolInterrupt+ ? 'incomplete'+ : finalState.status === 'error'+ ? 'failed'+ : 'completed',usage,});} catch (error) {@@ -288,7 +356,6 @@ export class ResponsesService extends BaseService {try {const model = params.model;- const prompt = this.extractPrompt(params.input);const instructions = this.buildInstructions(params);// Resolve topicId from previous_response_id for multi-turn@@ -296,15 +363,25 @@ export class ResponsesService extends BaseService {? this.extractTopicIdFromResponseId(params.previous_response_id): null;+ // Check for function_call_output resume flow+ const functionCallOutputs = this.extractFunctionCallOutputs(params.input);+ const isResumeFlow = functionCallOutputs.length > 0 && previousTopicId;++ const prompt = isResumeFlow+ ? this.buildToolResultPrompt(functionCallOutputs)+ : this.extractPrompt(params.input);+// 1. Create agent operation (before generating responseId so we have topicId)// model field is used as agentIdconst additionalPluginIds = this.extractHostedToolIds(params.tools);+ const functionTools = this.extractFunctionTools(params.tools);const aiAgentService = new AiAgentService(this.db, this.userId);const execResult = await aiAgentService.execAgent({additionalPluginIds: additionalPluginIds.length > 0 ? additionalPluginIds : undefined,agentId: model,appContext: previousTopicId ? { topicId: previousTopicId } : undefined,autoStart: false,+ functionTools: functionTools.length > 0 ? functionTools : undefined,instructions,prompt,stream: true,@@ -489,12 +566,17 @@ export class ResponsesService extends BaseService {// Emit function_call output items for each tool callfor (const toolCall of chunk.toolsCalling) {const fcItemId = `fc_${responseId}_${itemCounter++}`;+ // Client function tools use original name; hosted tools use identifier/apiName+ const isClientTool = toolCall.identifier === 'lobe-client-fn';+ const toolDisplayName = isClientTool+ ? toolCall.apiName+ : `${toolCall.identifier}/${toolCall.apiName}`;yield {item: {arguments: toolCall.arguments ?? '{}',call_id: toolCall.id,id: fcItemId,- name: `${toolCall.identifier}/${toolCall.apiName}`,+ name: toolDisplayName,status: 'in_progress' as const,type: 'function_call' as const,} as OutputItem,@@ -514,13 +596,22 @@ export class ResponsesService extends BaseService {};}+ // Emit arguments done+ yield {+ arguments: toolCall.arguments ?? '{}',+ item_id: fcItemId,+ output_index: currentOutputIndex,+ sequence_number: seq.n++,+ type: 'response.function_call_arguments.done' as const,+ };+// Complete the function_call itemyield {item: {arguments: toolCall.arguments ?? '{}',call_id: toolCall.id,id: fcItemId,- name: `${toolCall.identifier}/${toolCall.apiName}`,+ name: toolDisplayName,status: 'completed' as const,type: 'function_call' as const,} as OutputItem,@@ -594,24 +685,51 @@ export class ResponsesService extends BaseService {? this.extractOutputItems(finalState, responseId): { output: [], outputText: accumulatedText };- yield {- response: {- ...response,- completed_at: Math.floor(Date.now() / 1000),- output: fullOutput.output,- output_text: fullOutput.outputText || accumulatedText,- status: (finalState?.status === 'error' ? 'failed' : 'completed') as any,- usage: {- input_tokens: usage.input_tokens,- input_tokens_details: { cached_tokens: 0 },- output_tokens: usage.output_tokens,- output_tokens_details: { reasoning_tokens: 0 },- total_tokens: usage.total_tokens,+ // Determine if agent was interrupted for client tool execution+ const isClientToolInterrupt =+ finalState?.status === 'interrupted' &&+ finalState?.interruption?.reason === 'client_tool_execution';++ if (isClientToolInterrupt) {+ yield {+ response: {+ ...response,+ completed_at: null,+ incomplete_details: { reason: 'client_tool_execution' },+ output: fullOutput.output,+ output_text: fullOutput.outputText || accumulatedText,+ status: 'incomplete' as any,+ usage: {+ input_tokens: usage.input_tokens,+ input_tokens_details: { cached_tokens: 0 },+ output_tokens: usage.output_tokens,+ output_tokens_details: { reasoning_tokens: 0 },+ total_tokens: usage.total_tokens,+ },},- },- sequence_number: sequenceNumber,- type: 'response.completed' as const,- };+ sequence_number: sequenceNumber,+ type: 'response.incomplete' as const,+ };+ } else {+ yield {+ response: {+ ...response,+ completed_at: Math.floor(Date.now() / 1000),+ output: fullOutput.output,+ output_text: fullOutput.outputText || accumulatedText,+ status: (finalState?.status === 'error' ? 'failed' : 'completed') as any,+ usage: {+ input_tokens: usage.input_tokens,+ input_tokens_details: { cached_tokens: 0 },+ output_tokens: usage.output_tokens,+ output_tokens_details: { reasoning_tokens: 0 },+ total_tokens: usage.total_tokens,+ },+ },+ sequence_number: sequenceNumber,+ type: 'response.completed' as const,+ };+ }} catch (error) {const errorResponseId = this.generateResponseId();this.log('error', 'Streaming response failed', { error, responseId: errorResponseId });@@ -666,6 +784,7 @@ export class ResponsesService extends BaseService {createdAt: number;error?: { code: 'server_error'; message: string };id: string;+ incompleteDetails?: { reason: string };output: OutputItem[];outputText: string;params: CreateResponseRequest;@@ -680,7 +799,7 @@ export class ResponsesService extends BaseService {error: opts.error ?? null,frequency_penalty: p.frequency_penalty ?? 0,id: opts.id,- incomplete_details: null,+ incomplete_details: opts.incompleteDetails ?? null,instructions: opts.params.instructions ?? null,max_output_tokens: opts.params.max_output_tokens ?? null,max_tool_calls: p.max_tool_calls ?? null,diff --git a/packages/types/src/message/common/tools.ts b/packages/types/src/message/common/tools.tsindex 962f8168c86..e2a19224f7b 100644--- a/packages/types/src/message/common/tools.ts+++ b/packages/types/src/message/common/tools.ts@@ -26,7 +26,7 @@ export interface ChatPluginPayload {/*** Tool source indicates where the tool comes from*/-export type ToolSource = 'builtin' | 'plugin' | 'mcp' | 'klavis' | 'lobehubSkill';+export type ToolSource = 'builtin' | 'client' | 'plugin' | 'mcp' | 'klavis' | 'lobehubSkill';export interface ChatToolPayload {apiName: string;diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 526be6d486a..a07da06fa4c 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -1154,6 +1154,45 @@ export const createRuntimeExecutors = (const toolName = `${chatToolPayload.identifier}/${chatToolPayload.apiName}`;+ // Check if this is a client-side function tool β pause instead of executing+ const toolSource =+ state.operationToolSet?.sourceMap?.[chatToolPayload.identifier] ??+ state.toolSourceMap?.[chatToolPayload.identifier];++ 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 = 'interrupted';+ 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 configconst agentConfig = state.metadata?.agentConfig;const toolResultMaxLength = agentConfig?.chatConfig?.toolResultMaxLength;@@ -1370,13 +1409,61 @@ export const createRuntimeExecutors = (`[${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 = 'interrupted';+ 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 executionconst toolMessageIds: string[] = [];const toolResults: any[] = [];- // Execute all tools concurrently+ // Execute server tools concurrently (skip client tools in mixed batch)+ const toolsToExecute = serverTools.length > 0 ? serverTools : toolsCalling;await Promise.all(- toolsCalling.map(async (chatToolPayload: ChatToolPayload) => {+ toolsToExecute.map(async (chatToolPayload: ChatToolPayload) => {const toolName = `${chatToolPayload.identifier}/${chatToolPayload.apiName}`;// Publish tool execution start event@@ -1576,6 +1663,39 @@ export const createRuntimeExecutors = (// Get the last tool message ID as parentMessageId for next LLM callconst lastToolMessageId = toolMessageIds.at(-1);+ // If there are remaining client tools in a mixed batch, interrupt after server tools+ if (clientTools.length > 0) {+ log(+ `[${operationLogId}][call_tools_batch] Mixed batch: ${serverTools.length} server tools done, pausing for ${clientTools.length} client tools`,+ );++ await streamManager.publishStreamChunk(operationId, stepIndex, {+ chunkType: 'tools_calling',+ toolsCalling: clientTools as any,+ });++ newState.status = 'interrupted';+ newState.interruption = {+ canResume: true,+ interruptedAt: new Date().toISOString(),+ reason: 'client_tool_execution',+ };+ newState.pendingToolsCalling = clientTools;++ return {+ events: [+ ...events,+ {+ canResume: true,+ interruptedAt: new Date().toISOString(),+ reason: 'client_tool_execution',+ type: 'interrupted',+ },+ ],+ newState,+ };+ }+return {events,newState,diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.tsindex f175cd78a30..9c9d337794d 100644--- a/src/server/services/agentRuntime/types.ts+++ b/src/server/services/agentRuntime/types.ts@@ -1,5 +1,5 @@import { type AgentRuntimeContext, type AgentState } from '@lobechat/agent-runtime';-import type { LobeToolManifest, OperationSkillSet } from '@lobechat/context-engine';+import type { LobeToolManifest, OperationSkillSet, ToolSource } from '@lobechat/context-engine';import { type UserInterventionConfig } from '@lobechat/types';import { type ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';@@ -11,7 +11,7 @@ import { type AgentHook } from './hooks/types';export interface OperationToolSet {enabledToolIds?: string[];manifestMap: Record<string, LobeToolManifest>;- sourceMap?: Record<string, 'builtin' | 'plugin' | 'mcp' | 'klavis' | 'lobehubSkill'>;+ sourceMap?: Record<string, ToolSource>;tools?: any[];}diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 34ae4516ba8..da804ec3a9e 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -9,7 +9,7 @@ import {} from '@lobechat/builtin-tool-remote-device';import { builtinTools, manualModeExcludeToolIds } from '@lobechat/builtin-tools';import { LOADING_FLAT } from '@lobechat/const';-import type { LobeToolManifest } from '@lobechat/context-engine';+import type { LobeToolManifest, ToolSource } from '@lobechat/context-engine';import { SkillEngine } from '@lobechat/context-engine';import type { LobeChatDatabase } from '@lobechat/database';import type {@@ -117,6 +117,8 @@ interface InternalExecAgentParams extends ExecAgentParams {/** External URL β fetched if no buffer provided */url?: string;}>;+ /** Client-side function tools from Response API β injected into LLM with source='client' */+ functionTools?: Array<{ description?: string; name: string; parameters?: Record<string, any> }>;/** External lifecycle hooks (auto-adapt to local/production mode) */hooks?: AgentHook[];/** Maximum steps for the agent operation */@@ -230,6 +232,7 @@ export class AiAgentService {discordContext,existingMessageIds = [],files,+ functionTools,hooks,instructions,stepCallbacks,@@ -535,8 +538,7 @@ export class AiAgentService {});// Build toolSourceMap for routing tool execution- const toolSourceMap: Record<string, 'builtin' | 'plugin' | 'mcp' | 'klavis' | 'lobehubSkill'> =- {};+ const toolSourceMap: Record<string, ToolSource> = {};// Mark lobehub skillsfor (const manifest of lobehubSkillManifests) {toolSourceMap[manifest.identifier] = 'lobehubSkill';@@ -546,12 +548,40 @@ export class AiAgentService {toolSourceMap[manifest.identifier] = 'klavis';}+ // Inject client function tools from Response API+ const CLIENT_FN_IDENTIFIER = 'lobe-client-fn';+ if (functionTools?.length) {+ for (const ft of functionTools) {+ tools?.push({+ function: {+ description: ft.description,+ name: `${CLIENT_FN_IDENTIFIER}____${ft.name}`,+ parameters: ft.parameters,+ },+ type: 'function',+ });+ }+ toolSourceMap[CLIENT_FN_IDENTIFIER] = 'client';+ toolManifestMap[CLIENT_FN_IDENTIFIER] = {+ api: functionTools.map((ft) => ({+ description: ft.description ?? '',+ name: ft.name,+ parameters: ft.parameters ?? {},+ })),+ identifier: CLIENT_FN_IDENTIFIER,+ meta: { title: 'Client Functions' },+ type: 'default',+ };+ toolsResult.enabledToolIds.push(CLIENT_FN_IDENTIFIER);+ }+log(- 'execAgent: generated %d tools from %d configured plugins, %d lobehub skills, %d klavis tools',+ 'execAgent: generated %d tools from %d configured plugins, %d lobehub skills, %d klavis tools, %d client function tools',tools?.length ?? 0,pluginIds.length,lobehubSkillManifests.length,klavisManifests.length,+ functionTools?.length ?? 0,);// Override RemoteDevice manifest's systemRole with dynamic device list prompt