π€― 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(agent-runtime): reuse seeded assistant placeholder on tool-first resume (#16579)
Arvin Xu0b0199336614
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 0388c16e08c..d47360711fd 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -645,9 +645,13 @@ export class GeneralChatAgent implements Agent {return { reason: 'queued_message_interrupt', type: 'finish' };}- // No pending tools, continue to call LLM with tool results+ // No pending tools, continue to call LLM with tool results.+ // When this operation resumed by executing a tool first (e.g. the tools+ // activator), reuse the placeholder seeded for that resume so this turn+ // fills it instead of orphaning it (undefined for normal turns).return this.toLLMCall({+ assistantMessageId: state.pendingAssistantMessageId,messages: state.messages,model: this.config.modelRuntimeConfig?.model,parentMessageId,@@ -683,9 +687,13 @@ export class GeneralChatAgent implements Agent {return { reason: 'queued_message_interrupt', type: 'finish' };}- // No pending tools, continue to call LLM with tool results+ // No pending tools, continue to call LLM with tool results.+ // When this operation resumed by executing a tool first (e.g. the tools+ // activator), reuse the placeholder seeded for that resume so this turn+ // fills it instead of orphaning it (undefined for normal turns).return this.toLLMCall({+ assistantMessageId: state.pendingAssistantMessageId,messages: state.messages,model: this.config.modelRuntimeConfig?.model,parentMessageId,@@ -750,13 +758,24 @@ export class GeneralChatAgent implements Agent {// Context compression completed, continue to call LLMconst compressionPayload = context.payload as GeneralAgentCompressionResultPayload;- // If compression was skipped (no messages to compress), just call LLM- // Otherwise, messages have been updated with compressed content- // Pass parentMessageId and createAssistantMessage=true to force new message creation+ // A tool-first resume seeds an assistant placeholder that the first+ // post-tool LLM turn must fill. When that turn is large enough to+ // compress first, the compress_context step (not a call_llm) leaves the+ // seed unconsumed, so it reaches here still set β reuse it instead of+ // forcing a new message, otherwise the placeholder is orphaned for+ // exactly the high-context cases that trigger compression.+ //+ // If compression was skipped (no messages to compress), just call LLM.+ // Otherwise, messages have been updated with compressed content, and a+ // normal turn forces a fresh assistant message.+ const seededAssistantMessageId = state.pendingAssistantMessageId;+return {payload: {- // Force create new assistant message after compression- createAssistantMessage: true,+ ...(seededAssistantMessageId+ ? { assistantMessageId: seededAssistantMessageId }+ : // Force create new assistant message after compression+ { createAssistantMessage: true }),messages: compressionPayload.compressedMessages,model: this.config.modelRuntimeConfig?.model,parentMessageId: compressionPayload.parentMessageId,diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex abb842fc23e..6a1afd43845 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -746,6 +746,44 @@ describe('GeneralChatAgent', () => {});});+ // Resume-seeded placeholder reuse: when an operation resumes by executing a+ // tool first (e.g. the tools activator auto-approved via human_approved_tool),+ // the seeded assistant placeholder is stashed on state.pendingAssistantMessageId.+ // The first call_llm after the tool result must carry it so the LLM turn fills+ // that placeholder instead of creating a new message and orphaning the seed.+ it('should reuse the seeded assistant placeholder for the first call_llm after a tool result', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const state = createMockState({+ messages: [+ { role: 'user', content: 'Hello' },+ { role: 'assistant', content: '', tools: [] },+ { role: 'tool', content: 'Successfully activated tools', tool_call_id: 'call-1' },+ ] as any,+ pendingAssistantMessageId: 'msg_seeded_placeholder',+ });++ const context = createMockContext('tool_result', { parentMessageId: 'tool-msg-1' });++ const result = await agent.runner(context, state);++ expect(result).toEqual({+ type: 'call_llm',+ payload: {+ assistantMessageId: 'msg_seeded_placeholder',+ messages: state.messages,+ model: 'gpt-4o-mini',+ parentMessageId: 'tool-msg-1',+ provider: 'openai',+ tools: undefined,+ },+ });+ });+it('should return compress_context before continuing to LLM when tool results exceed window', async () => {const agent = createCompressionAgent();@@ -1877,6 +1915,49 @@ describe('GeneralChatAgent', () => {},});});++ // High-context tool-first resume: when the first post-tool turn compresses+ // before running, the seeded placeholder must still be reused after+ // compression rather than orphaned by createAssistantMessage.+ it('should reuse the seeded assistant placeholder instead of forcing a new message', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const compressedMessages = [+ { content: 'Compressed summary', id: 'group-1', role: 'compressedGroup' },+ { content: 'Latest user follow-up', role: 'user' },+ ] as any;++ const state = createMockState({+ pendingAssistantMessageId: 'msg_seeded_placeholder',+ tools: [{ name: 'search' }] as any,+ });++ const context = createMockContext('compression_result', {+ compressedMessages,+ parentMessageId: 'tool-msg-1',+ skipped: false,+ });++ const result = await agent.runner(context, state);++ expect(result).toEqual({+ type: 'call_llm',+ payload: {+ assistantMessageId: 'msg_seeded_placeholder',+ messages: compressedMessages,+ model: 'gpt-4o-mini',+ parentMessageId: 'tool-msg-1',+ provider: 'openai',+ tools: state.tools,+ },+ });+ // Must not also force a brand-new message when reusing the placeholder.+ expect((result as any).payload.createAssistantMessage).toBeUndefined();+ });});describe('unknown phase', () => {diff --git a/packages/agent-runtime/src/core/__tests__/runtime.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.test.tsindex 50f10e92702..03144e973e1 100644--- a/packages/agent-runtime/src/core/__tests__/runtime.test.ts+++ b/packages/agent-runtime/src/core/__tests__/runtime.test.ts@@ -338,6 +338,70 @@ describe('AgentRuntime', () => {'Tool not found: unknown_tool',);});++ // A resume that carries a seeded assistant placeholder must stash it on+ // state so the follow-up call_llm reuses it β otherwise the placeholder is+ // orphaned as an empty assistant sibling. See the tools-activator op-split.+ it('should stash the resume-seeded assistantMessageId as pendingAssistantMessageId', async () => {+ const agent = new MockAgent();+ agent.tools = {+ calculator: vi.fn().mockResolvedValue({ result: 42 }),+ };++ const runtime = new AgentRuntime(agent);+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });++ const result = await runtime.step(state, {+ operationId: 'test-session',+ phase: 'human_approved_tool',+ payload: {+ approvedToolCall: {+ id: 'call_123',+ apiName: 'calculator',+ identifier: 'calculator',+ arguments: '{"expression": "2+2"}',+ type: 'default',+ },+ assistantMessageId: 'msg_seeded_placeholder',+ parentMessageId: 'tool-msg-1',+ skipCreateToolMessage: true,+ },+ session: {+ sessionId: 'test-session',+ messageCount: 0,+ status: 'idle',+ stepCount: 0,+ },+ } as any);++ expect(result.newState.pendingAssistantMessageId).toBe('msg_seeded_placeholder');+ });++ // Consume-once: once a call_llm step runs it has filled (or replaced) the+ // seeded placeholder, so the seed must be cleared before the next step β+ // otherwise a later assistant turn would reuse the id and overwrite it.+ it('should clear pendingAssistantMessageId after a call_llm step', async () => {+ const agent = new MockAgent();+ const callLlmExecutor = vi.fn(async (_instruction: any, state: AgentState) => ({+ events: [],+ newState: structuredClone(state),+ }));++ const runtime = new AgentRuntime(agent, {+ executors: { call_llm: callLlmExecutor },+ });+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });+ state.pendingAssistantMessageId = 'msg_seeded_placeholder';++ // MockAgent.runner returns a call_llm instruction for the tool_result phase.+ const result = await runtime.step(+ state,+ createTestContext('tool_result', { parentMessageId: 'tool-msg-1' }),+ );++ expect(callLlmExecutor).toHaveBeenCalled();+ expect(result.newState.pendingAssistantMessageId).toBeUndefined();+ });});describe('human interaction executors', () => {diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.tsindex 4b411fd5b59..a13d5eb581b 100644--- a/packages/agent-runtime/src/core/runtime.ts+++ b/packages/agent-runtime/src/core/runtime.ts@@ -111,11 +111,23 @@ export class AgentRuntime {if (runtimeContext.phase === 'human_approved_tool') {const approvedPayload = runtimeContext.payload as {approvedToolCall: ChatToolPayload;+ assistantMessageId?: string;parentMessageId: string;skipCreateToolMessage: boolean;};const toolCalling = approvedPayload.approvedToolCall;+ // The resume seeded an assistant placeholder (assistantMessageId) for+ // this operation, but the first instruction here is a tool execution β+ // not an LLM call β so nothing consumes the placeholder and it would be+ // left as an empty orphan sibling once the follow-up call_llm creates+ // its own message. Stash the id on state so the first call_llm after+ // the tool result reuses the placeholder instead (consumed once, then+ // cleared in the instruction loop below).+ if (approvedPayload.assistantMessageId) {+ newState.pendingAssistantMessageId = approvedPayload.assistantMessageId;+ }+rawInstructions = {payload: {parentMessageId: approvedPayload.parentMessageId,@@ -194,6 +206,14 @@ export class AgentRuntime {// Update statecurrentState = result.newState;+ // 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+ // turn in the same operation would reuse the id and overwrite this one.+ if (instruction.type === 'call_llm' && currentState.pendingAssistantMessageId) {+ currentState.pendingAssistantMessageId = undefined;+ }+// Keep the last nextContextif (result.nextContext) {finalNextContext = result.nextContext;diff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.tsindex 4be58010f3d..c0a0747eb99 100644--- a/packages/agent-runtime/src/types/generalAgent.ts+++ b/packages/agent-runtime/src/types/generalAgent.ts@@ -6,6 +6,12 @@ import {} from '@lobechat/types';export interface GeneralAgentCallLLMInstructionPayload {+ /**+ * Reuse an existing assistant message instead of creating a new one. Set when+ * resuming from a tool-first step (e.g. tools activator) whose seeded+ * placeholder must be filled by this LLM turn rather than orphaned.+ */+ assistantMessageId?: string;/** Force create a new assistant message (e.g., after compression) */createAssistantMessage?: boolean;isFirstMessage?: boolean;diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex 9273285b710..b9d4bcb17e4 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -91,15 +91,23 @@ export interface AgentState {/** Operation-level tool set snapshot (immutable after creation) */operationToolSet?: OperationToolSet;+ // --- HIL ---+ /**+ * Assistant placeholder seeded for a resume that starts by executing a tool+ * (e.g. a human-approved / auto-approved tool such as the tools activator).+ * The first `call_llm` after that tool consumes this id so its output reuses+ * the placeholder instead of creating a new message and orphaning the seed.+ * Cleared once consumed.+ */+ pendingAssistantMessageId?: string;pendingHumanPrompt?: { metadata?: Record<string, unknown>; prompt: string };+pendingHumanSelect?: {metadata?: Record<string, unknown>;multi?: boolean;options: Array<{ label: string; value: string }>;prompt?: string;};-- // --- HIL ---/*** When status is 'waiting_for_human', this stores pending requests* for human-in-the-loop operations.