π€― 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
π fix(model-runtime): keep parallel tool-call arguments on their own call (#22718)
Lobehub Coder0b7314a86eea
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 73b8db4ef4b..09e109ca81b 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -27,6 +27,7 @@ import {type SubAgentsBatchResultPayload,} from '../types';import {+ buildEmptyArgsToolContent,EMPTY_ARGS_TOOL_CONTENT,EMPTY_ARGS_TOOL_REASON,partitionEmptyArgumentsCalls,@@ -681,6 +682,9 @@ export class GeneralChatAgent implements Agent {instructions.push({payload: {blockedContent: EMPTY_ARGS_TOOL_CONTENT,+ blockedContentByCallId: Object.fromEntries(+ emptyArgsCalls.map((call) => [call.id, buildEmptyArgsToolContent(call)]),+ ),blockedReason: EMPTY_ARGS_TOOL_REASON,parentMessageId,toolsCalling: emptyArgsCalls,diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.emptyArguments.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.emptyArguments.test.tsindex 819c48e42e7..bcb91aa565c 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.emptyArguments.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.emptyArguments.test.ts@@ -234,6 +234,11 @@ describe('GeneralChatAgent empty-arguments handling (llm_result phase)', () => {{payload: {blockedContent: expect.stringContaining('arguments of this call arrived empty'),+ blockedContentByCallId: {+ 'call-1': expect.stringContaining(+ 'arguments of this call (tool: lobe-acceptance-evidence.submitEvidence, call id: call-1) arrived empty',+ ),+ },blockedReason: 'tool_arguments_empty',parentMessageId: 'msg-1',toolsCalling: [requiredArgsCall],diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 270eed380cb..35b1cbdb35d 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -965,8 +965,7 @@ describe('GeneralChatAgent', () => {it('rejects parallel-batch calls that arrived with empty arguments instead of executing them', async () => {const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));- // The serialization-loss shape from T-673: fully-formed parallel calls- // whose per-call arguments were lost upstream, reaching the agent as ''.+ // T-673 loss shape: fully-formed parallel calls whose arguments arrived as ''.const lostArgsCalls: ChatToolPayload[] = [{apiName: 'search',@@ -997,6 +996,7 @@ describe('GeneralChatAgent', () => {{payload: {blockedContent: expect.stringContaining('arguments of this call arrived empty'),+ blockedContentByCallId: expect.any(Object),blockedReason: 'tool_arguments_empty',parentMessageId: 'msg-1',toolsCalling: lostArgsCalls,@@ -1030,8 +1030,7 @@ describe('GeneralChatAgent', () => {parentMessageId: 'msg-1',toolsCalling: [lostArgsCall, healthyCall],}),- // Manifests without humanIntervention config β no intervention, so the- // healthy call goes straight to the executor.+ // No humanIntervention config β the healthy call goes straight to the executor.createMockState({toolManifestMap: {'lobe-web-browsing': { identifier: 'lobe-web-browsing' },@@ -1044,6 +1043,7 @@ describe('GeneralChatAgent', () => {{payload: {blockedContent: expect.stringContaining('Call the tool again one call at a time'),+ blockedContentByCallId: expect.any(Object),blockedReason: 'tool_arguments_empty',parentMessageId: 'msg-1',toolsCalling: [lostArgsCall],diff --git a/packages/agent-runtime/src/core/__tests__/runtime.blockedTools.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.blockedTools.test.tsnew file mode 100644index 00000000000..9e5bfba076b--- /dev/null+++ b/packages/agent-runtime/src/core/__tests__/runtime.blockedTools.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import type { Agent, AgentRuntimeContext, AgentState } from '../../types';+import { AgentRuntime } from '../runtime';++const blockedCall = (id: string) => ({+ apiName: 'readFile',+ arguments: '',+ id,+ identifier: 'lobe-local-system',+ type: 'builtin' as const,+});++describe('AgentRuntime resolve_blocked_tools per-call content', () => {+ it('writes the per-call content for calls that have one and the shared content otherwise', async () => {+ class BlockedToolAgent implements Agent {+ async runner(context: AgentRuntimeContext, _state: AgentState) {+ if (context.phase === 'user_input') {+ return {+ payload: {+ blockedContent: 'shared rejection',+ blockedContentByCallId: { call_a: 'rejection naming call_a' },+ blockedReason: 'tool_arguments_empty',+ parentMessageId: 'assistant-1',+ toolsCalling: [blockedCall('call_a'), blockedCall('call_b')],+ },+ type: 'resolve_blocked_tools' as const,+ };+ }++ return { reason: 'completed' as const, type: 'finish' as const };+ }+ }++ const runtime = new AgentRuntime(new BlockedToolAgent());+ const state = AgentRuntime.createInitialState({+ messages: [{ content: 'Read two files', role: 'user' }],+ operationId: 'blocked-per-call-test',+ });++ const result = await runtime.step(state);++ const contentById = Object.fromEntries(+ result.events.map((event: any) => [event.id, event.result.content]),+ );+ expect(contentById).toEqual({+ call_a: 'rejection naming call_a',+ call_b: 'shared rejection',+ });+ expect(result.newState.messages.filter((m) => m.role === 'tool')).toEqual([+ { content: 'rejection naming call_a', role: 'tool', tool_call_id: 'call_a' },+ { content: 'shared rejection', role: 'tool', tool_call_id: 'call_b' },+ ]);+ });+});diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.tsindex 3493e841132..7f16c6cf89c 100644--- a/packages/agent-runtime/src/core/runtime.ts+++ b/packages/agent-runtime/src/core/runtime.ts@@ -284,7 +284,6 @@ export class AgentRuntime {currentState = result.newState;latestState = currentState;-// A call_llm consumes any resume-seeded assistant placeholder exactly// once β it has now either reused that message id or created its own β// so clear the seed before the next step. Otherwise a later assistant@@ -755,7 +754,10 @@ export class AgentRuntime {for (const toolCalling of payload.toolsCalling) {const result = {- content: payload.blockedContent ?? 'Blocked by security/privacy.',+ content:+ payload.blockedContentByCallId?.[toolCalling.id] ??+ payload.blockedContent ??+ 'Blocked by security/privacy.',...(payload.blockedReason && { error: payload.blockedReason }),success: false,};diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.tsindex dc0063631c7..882a0ed1d0c 100644--- a/packages/agent-runtime/src/executors/resolveTools.test.ts+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts@@ -166,6 +166,28 @@ describe('resolveTools executors', () => {);});+ it('writes the per-call blocked content when one is given for the call id', async () => {+ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {+ payload: {+ blockedContent: 'generic rejection',+ blockedContentByCallId: { 'tool-call-1': 'rejection naming tool-call-1' },+ blockedReason: 'tool_arguments_empty',+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall()],+ },+ type: 'resolve_blocked_tools',+ };++ const result = await resolveBlockedTools(host)(instruction, createState());++ expect(host.transports.messages.createToolMessage).toHaveBeenCalledWith(+ expect.objectContaining({ content: 'rejection naming tool-call-1' }),+ );+ expect(result.newState.messages).toContainEqual(+ expect.objectContaining({ content: 'rejection naming tool-call-1', role: 'tool' }),+ );+ });+// Without this write the rejection is lost: state messages are rebuilt from// the DB every step, and conversation-flow only collects a tool row whose// parent assistant lists the matching call.diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.tsindex fb05ad02962..985a164165b 100644--- a/packages/agent-runtime/src/executors/resolveTools.ts+++ b/packages/agent-runtime/src/executors/resolveTools.ts@@ -71,7 +71,7 @@ export const resolveBlockedTools =for (const toolPayload of payload.toolsCalling) {const result: ToolRunResult = {- content: blockedContent,+ content: payload.blockedContentByCallId?.[toolPayload.id] ?? blockedContent,error: blockedReason,executionTime: 0,state: {diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.tsindex 35bcb096262..bf3decb7b4d 100644--- a/packages/agent-runtime/src/types/instruction.ts+++ b/packages/agent-runtime/src/types/instruction.ts@@ -304,6 +304,12 @@ export interface AgentInstructionResolveBlockedTools extends AgentInstructionBaspayload: {/** Optional message to write into blocked tool result content */blockedContent?: string;+ /**+ * Per-call override of {@link blockedContent}, keyed by tool call id, for+ * rejections whose message must name the specific call (tool + call id).+ * A plain record so the instruction stays serializable.+ */+ blockedContentByCallId?: Record<string, string>;/** Optional machine-readable blocked reason */blockedReason?: string;/** Parent message ID (assistant message) */diff --git a/packages/agent-runtime/src/utils/emptyArgumentsCalls.test.ts b/packages/agent-runtime/src/utils/emptyArgumentsCalls.test.tsindex 1b83feb8e5c..4d747475e90 100644--- a/packages/agent-runtime/src/utils/emptyArgumentsCalls.test.ts+++ b/packages/agent-runtime/src/utils/emptyArgumentsCalls.test.ts@@ -2,7 +2,12 @@ import type { ChatToolPayload } from '@lobechat/types';import { describe, expect, it } from 'vitest';import type { AgentState } from '../types';-import { partitionEmptyArgumentsCalls, toolExpectsNoArguments } from './emptyArgumentsCalls';+import {+ buildEmptyArgsToolContent,+ EMPTY_ARGS_TOOL_CONTENT,+ partitionEmptyArgumentsCalls,+ toolExpectsNoArguments,+} from './emptyArgumentsCalls';const makeState = (manifestMap: Record<string, unknown> = {}): AgentState =>({ toolManifestMap: manifestMap }) as unknown as AgentState;@@ -180,3 +185,17 @@ describe('partitionEmptyArgumentsCalls', () => {expect(result.emptyArgsCalls).toEqual([unknown]);});});++describe('buildEmptyArgsToolContent', () => {+ it('names the tool and call id so a rejected parallel call is diagnosable', () => {+ const content = buildEmptyArgsToolContent(+ call({ apiName: 'writeFile', id: 'call_7', identifier: 'lobe-local-system' }),+ );++ expect(content).toContain(+ 'the arguments of this call (tool: lobe-local-system.writeFile, call id: call_7) arrived empty',+ );+ expect(content).toContain('The call was not executed.');+ expect(content).not.toBe(EMPTY_ARGS_TOOL_CONTENT);+ });+});diff --git a/packages/agent-runtime/src/utils/emptyArgumentsCalls.ts b/packages/agent-runtime/src/utils/emptyArgumentsCalls.tsindex b344e256fb9..3a2d643fb99 100644--- a/packages/agent-runtime/src/utils/emptyArgumentsCalls.ts+++ b/packages/agent-runtime/src/utils/emptyArgumentsCalls.ts@@ -18,6 +18,21 @@ export const EMPTY_ARGS_TOOL_CONTENT ='Tool call rejected: the arguments of this call arrived empty β the parameters were lost before execution, a known failure mode when several tool calls are emitted in parallel. The call was not executed. Call the tool again one call at a time and include the complete arguments JSON for the call.';export const EMPTY_ARGS_TOOL_REASON = 'tool_arguments_empty';+/**+ * Per-call variant of {@link EMPTY_ARGS_TOOL_CONTENT} that names the tool and+ * the call id, so a rejected row in a parallel batch is diagnosable on its own+ * (which call lost its arguments) instead of N identical messages.+ */+export const buildEmptyArgsToolContent = (toolCalling: ChatToolPayload): string => {+ const toolName = toolCalling.apiName+ ? `${toolCalling.identifier}.${toolCalling.apiName}`+ : toolCalling.identifier;+ return EMPTY_ARGS_TOOL_CONTENT.replace(+ 'the arguments of this call arrived empty',+ `the arguments of this call (tool: ${toolName}, call id: ${toolCalling.id}) arrived empty`,+ );+};+/*** JSON Schema keywords that cannot make an object with no properties* invalid, and are therefore safe to ignore when proving that `{}` is adiff --git a/packages/model-runtime/src/core/streams/openai/openai.parallelToolCalls.test.ts b/packages/model-runtime/src/core/streams/openai/openai.parallelToolCalls.test.tsnew file mode 100644index 00000000000..556051596db--- /dev/null+++ b/packages/model-runtime/src/core/streams/openai/openai.parallelToolCalls.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest';++import type { MessageToolCall } from '../../../types';+import { createReadableStream, readStreamChunk } from '../utils';+import { OpenAIStream } from './openai';++const toolChunk = (toolCall: Record<string, unknown>) => ({+ choices: [{ delta: { tool_calls: [toolCall] }, index: 0 }],+ id: 'chatcmpl-test',+});++const collectToolCalls = async (chunks: unknown[]) => {+ let final: MessageToolCall[] = [];+ const stream = OpenAIStream(createReadableStream(chunks), {+ callbacks: {+ onToolsCalling: ({ toolsCalling }) => {+ final = toolsCalling;+ },+ },+ });+ await readStreamChunk(stream);+ return final.map((call) => ({+ arguments: call.function.arguments,+ id: call.id,+ name: call.function.name,+ }));+};++/**+ * Parallel tool calls whose opening delta carries the call id but no name+ * (NVIDIA NIM / some OpenAI-compatible proxies send `name: null` as a+ * start-of-call marker). Continuation deltas carry only `index`. They must be+ * routed by index to their own call, not to the first call's id β otherwise+ * every call after the first finishes with empty arguments ("the arguments of+ * this call arrived empty") and the first gets the concatenation of all.+ */+describe('OpenAIStream parallel tool calls without name on the opening delta', () => {+ it('routes index-only argument deltas to their own call', async () => {+ const result = await collectToolCalls([+ toolChunk({ function: { arguments: '', name: null }, id: 'call_a', index: 0 }),+ toolChunk({ function: { name: 'readFile' }, index: 0 }),+ toolChunk({ function: { arguments: '{"path":"/a"}' }, index: 0 }),+ toolChunk({ function: { arguments: '', name: null }, id: 'call_b', index: 1 }),+ toolChunk({ function: { name: 'readFile' }, index: 1 }),+ toolChunk({ function: { arguments: '{"path":"/b"}' }, index: 1 }),+ toolChunk({ function: { arguments: '', name: null }, id: 'call_c', index: 2 }),+ toolChunk({ function: { name: 'grep' }, index: 2 }),+ toolChunk({ function: { arguments: '{"pattern":"x"}' }, index: 2 }),+ ]);++ expect(result).toEqual([+ { arguments: '{"path":"/a"}', id: 'call_a', name: 'readFile' },+ { arguments: '{"path":"/b"}', id: 'call_b', name: 'readFile' },+ { arguments: '{"pattern":"x"}', id: 'call_c', name: 'grep' },+ ]);+ });++ it('routes interleaved index-only deltas when names arrive with the id', async () => {+ const result = await collectToolCalls([+ toolChunk({ function: { arguments: '', name: 'readFile' }, id: 'call_a', index: 0 }),+ toolChunk({ function: { arguments: '', name: 'grep' }, id: 'call_b', index: 1 }),+ toolChunk({ function: { arguments: '{"path":' }, index: 0 }),+ toolChunk({ function: { arguments: '{"pattern":"x"}' }, index: 1 }),+ toolChunk({ function: { arguments: '"/a"}' }, index: 0 }),+ ]);++ expect(result).toEqual([+ { arguments: '{"path":"/a"}', id: 'call_a', name: 'readFile' },+ { arguments: '{"pattern":"x"}', id: 'call_b', name: 'grep' },+ ]);+ });+});diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/streams/openai/openai.tsindex 78cfa4a9df2..c744b703080 100644--- a/packages/model-runtime/src/core/streams/openai/openai.ts+++ b/packages/model-runtime/src/core/streams/openai/openai.ts@@ -208,14 +208,19 @@ const transformOpenAIStream = (// Determine the actual tool indexconst toolIndex = typeof value.index !== 'undefined' ? value.index : mapIndex;- // Store tool info by index for parallel tool calls (e.g., GPT-5.2)- // When a chunk has id and name, it's the start of a new tool call- if (streamContext && value.id && value.function?.name) {+ // Store tool info by index for parallel tool calls (e.g., GPT-5.2).+ // Any chunk carrying an id starts (or re-identifies) the call at this+ // index β including opening deltas whose name is still null/'' (NVIDIA+ // NIM and some OpenAI-compatible proxies send the name in a later+ // delta). Requiring a name here left those indices unmapped, so their+ // id-less argument deltas fell back to the FIRST call's id: every+ // later call in the batch ended with empty arguments.+ if (streamContext && value.id) {if (!streamContext.tools) streamContext.tools = {};streamContext.tools[toolIndex] = {id: value.id,index: toolIndex,- name: value.function.name,+ name: value.function?.name || '',};}@@ -233,11 +238,12 @@ const transformOpenAIStream = (arguments: value.function?.arguments ?? '',name: value.function?.name ?? null,},- // Priority: explicit id > tools map by index > single tool fallback > generated id+ // Priority: explicit id > tools map by index > generated id.+ // Never fall back to another index's id: that merges this delta's+ // arguments into a different call of the same parallel batch.id:value.id ||streamContext?.tools?.[toolIndex]?.id ||- streamContext?.tool?.id ||generateToolCallId(mapIndex, value.function?.name),// mistral's tool calling don't have index and function field, it's data like: