🤯 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
♻️ refactor: define prepared call llm turn boundary (#17014)
Arvin Xu2f6929f0f5e7
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.tsnew file mode 100644index 00000000000..617a45ef2e1--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.ts@@ -0,0 +1,37 @@+import type {+ ContextBuilder,+ ContextBuildInput,+ ContextBuildOutput,+} from '@lobechat/agent-runtime';++import type { RuntimeExecutorContext } from '../context';+import { buildServerCallLlmContext } from './serverCallLlmContextBuilder';+import { resolveServerCallLlmTooling } from './serverCallLlmTooling';++export class ServerContextBuilder implements ContextBuilder {+ constructor(private readonly ctx: RuntimeExecutorContext) {}++ async build(input: ContextBuildInput): Promise<ContextBuildOutput> {+ const tooling = resolveServerCallLlmTooling(+ this.ctx,+ input.state,+ input.payload.allowedToolNames,+ );+ const result = await buildServerCallLlmContext({+ ctx: this.ctx,+ llmPayload: input.payload,+ model: input.model,+ provider: input.provider,+ state: input.state,+ tooling,+ });++ return {+ messages: result.processedMessages,+ modelParameters: result.resolvedExtendParams,+ preserveThinking: result.preserveThinkingForPayload,+ replayAssistantReasoning: result.shouldReplayAssistantReasoning,+ resolvedTools: tooling.resolved,+ };+ }+}diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex 857155e737e..445f8d8f5c7 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -1,16 +1,15 @@import type {- LLMCallExecuteInput,LLMStreamPayload,LLMStreamResult,LLMTransport,+ LLMTurnInput,} from '@lobechat/agent-runtime';import { consumeStreamUntilDone } from '@lobechat/model-runtime';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import type { RuntimeExecutorContext } from '../context';-import { callLlm as createServerCallLlmExecutor } from './serverCallLlmExecutor';-import { resolveServerCallLlmTooling } from './serverCallLlmTooling';+import { executeServerCallLlmTurn } from './serverCallLlmExecutor';const getErrorMessage = (error: unknown): string => {if (error instanceof Error && error.message) return error.message;@@ -29,18 +28,15 @@ const getErrorMessage = (error: unknown): string => {export class ServerLLMTransport implements LLMTransport {constructor(private readonly ctx: RuntimeExecutorContext) {}- executeCall(input: LLMCallExecuteInput): ReturnType<NonNullable<LLMTransport['executeCall']>> {- return createServerCallLlmExecutor(this.ctx, {+ executeTurn(input: LLMTurnInput): ReturnType<NonNullable<LLMTransport['executeTurn']>> {+ return executeServerCallLlmTurn(this.ctx, {assistantMessage: input.assistantMessage,+ context: input.context,model: input.model,provider: input.provider,+ state: input.state,stepLabel: input.stepLabel,- tooling: resolveServerCallLlmTooling(- this.ctx,- input.state,- input.instruction.payload.allowedToolNames,- ),- })(input.instruction, input.state);+ });}async stream(diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.tsindex a928be65a1a..7c4e1c4e4f1 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts@@ -1,10 +1,10 @@import {type AgentEvent,- type AgentInstruction,- type CallLLMPayload,+ type AgentState,+ type ContextBuildOutput,type GeneralAgentCallLLMResultPayload,getLLMRetryDelayMs,- type InstructionExecutor,+ type InstructionExecutionResult,resolveLLMMaxAttempts,resolveLLMRetryBudget,shouldRetryLLM,@@ -31,19 +31,18 @@ import { isOperationInterrupted, log, sleep } from '../executorHelpers';import { formatErrorEventData } from '../formatErrorEventData';import { classifyLLMError } from '../llmErrorClassification';import { createServerCallLlmAttempt } from './serverCallLlmAttempt';-import { buildServerCallLlmContext } from './serverCallLlmContextBuilder';import {finalizeServerCallLlmResult,persistInterruptedServerCallLlmResult,} from './serverCallLlmFinalizer';-import type { ServerCallLlmTooling } from './serverCallLlmTooling';interface ServerCallLlmExecutionContext {assistantMessage: { id: string };+ context: ContextBuildOutput;model: string;provider: string;+ state: AgentState;stepLabel?: string;- tooling: ServerCallLlmTooling;}const SERVER_LLM_RETRY_POLICY = {@@ -51,22 +50,33 @@ const SERVER_LLM_RETRY_POLICY = {noRetryProviders: [BRANDING_PROVIDER],};-export const callLlm =- (ctx: RuntimeExecutorContext, prepared: ServerCallLlmExecutionContext): InstructionExecutor =>- async (instruction, state) => {- const { payload } = instruction as Extract<AgentInstruction, { type: 'call_llm' }>;- const llmPayload = payload as CallLLMPayload;+class ServerCallLlmTurn {+ constructor(+ private readonly ctx: RuntimeExecutorContext,+ private readonly prepared: ServerCallLlmExecutionContext,+ ) {}++ async execute(): Promise<InstructionExecutionResult> {+ const { ctx, prepared } = this;+ const { state } = prepared;const { operationId, stepIndex, streamManager } = ctx;const events: AgentEvent[] = [];let visibleOutputEndPublishedStepIndex: number | undefined;const {assistantMessage: assistantMessageItem,+ context,model,provider,stepLabel,- tooling,} = prepared;- const { resolved, tools } = tooling;+ const {+ messages: preparedMessages,+ modelParameters: resolvedExtendParams,+ preserveThinking: preserveThinkingForPayload,+ replayAssistantReasoning: shouldReplayAssistantReasoning,+ resolvedTools: resolved,+ } = context;+ const processedMessages = preparedMessages as ChatStreamPayload['messages'];const operationLogId = `${operationId}:${stepIndex}`;log('[%s][call_llm] Starting operation with prepared assistant message: %s',@@ -75,19 +85,8 @@ export const callLlm =);try {- const {- preserveThinkingForPayload,- processedMessages,- resolvedExtendParams,- shouldReplayAssistantReasoning,- } = await buildServerCallLlmContext({- ctx,- llmPayload,- model,- provider,- state,- tooling,- });+ if (!resolved) throw new Error('Resolved tools are required for a server LLM turn');+ const tools = resolved.tools.length > 0 ? resolved.tools : undefined;// A turn must carry at least one non-system message. Anthropic-compatible// providers (anthropic / deepseek) move `role: system` into a separate@@ -393,4 +392,10 @@ export const callLlm =);throw error;}- };+ }+}++export const executeServerCallLlmTurn = (+ ctx: RuntimeExecutorContext,+ prepared: ServerCallLlmExecutionContext,+): Promise<InstructionExecutionResult> => new ServerCallLlmTurn(ctx, prepared).execute();diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.tsindex 55fec1f0c7d..dab155aade4 100644--- a/apps/server/src/modules/AgentRuntime/buildHost.ts+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts@@ -1,6 +1,7 @@import type { AgentRuntimeHost } from '@lobechat/agent-runtime';import { ServerCompressionTransport } from './adapters/ServerCompressionTransport';+import { ServerContextBuilder } from './adapters/ServerContextBuilder';import { ServerLifecycleSink } from './adapters/ServerLifecycleSink';import { ServerLLMTransport } from './adapters/ServerLLMTransport';import { ServerMessageTransport } from './adapters/ServerMessageTransport';@@ -39,6 +40,7 @@ export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => ({compression: ctx.userId? new ServerCompressionTransport(ctx.serverDB, ctx.userId, ctx.workspaceId): undefined,+ context: new ServerContextBuilder(ctx),llm: ctx.userId ? new ServerLLMTransport(ctx) : undefined,messages: new ServerMessageTransport(ctx.messageModel, {postProcessUrl: buildPostProcessUrl(ctx),diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.tsindex 6dbe4765cd5..d31e18654b7 100644--- a/packages/agent-runtime/src/executors/callLlm.test.ts+++ b/packages/agent-runtime/src/executors/callLlm.test.ts@@ -1,6 +1,13 @@import { describe, expect, it, vi } from 'vitest';-import type { AgentRuntimeHost, LLMTransport, MessageTransport, StreamSink } from '../transport';+import type {+ AgentRuntimeHost,+ ContextBuilder,+ ContextBuildOutput,+ LLMTransport,+ MessageTransport,+ StreamSink,+} from '../transport';import type { AgentInstructionCallLlm, AgentState } from '../types';import { callLlm } from './callLlm';@@ -67,16 +74,28 @@ const createMessageTransport = (): MessageTransport => ({const createStreamSink = (): StreamSink => ({publishChunk: vi.fn(),+ publishError: vi.fn(),publishEvent: vi.fn(),});+const contextOutput: ContextBuildOutput = {+ messages: [{ content: 'prepared hello', role: 'user' }],+ replayAssistantReasoning: false,+};++const createContextBuilder = (): ContextBuilder => ({+ build: vi.fn().mockResolvedValue(contextOutput),+});+const createHost = (llm: LLMTransport,messages = createMessageTransport(),stream = createStreamSink(),+ context = createContextBuilder(),): AgentRuntimeHost => ({operation: { operationId: 'op-1', stepIndex: 0 },transports: {+ context,llm,messages,stream,@@ -90,16 +109,18 @@ describe('callLlm executor', () => {events: [],newState: state,};- const executeCall = vi.fn().mockResolvedValue(expected);+ const executeTurn = vi.fn().mockResolvedValue(expected);const messages = createMessageTransport();const stream = createStreamSink();+ const context = createContextBuilder();const host = createHost({- executeCall,+ executeTurn,stream: vi.fn(),},messages,stream,+ context,);const instructionWithParent: AgentInstructionCallLlm = {payload: {@@ -132,9 +153,15 @@ describe('callLlm executor', () => {stepIndex: 0,type: 'stream_start',});- expect(executeCall).toHaveBeenCalledWith({+ expect(context.build).toHaveBeenCalledWith({+ model: 'gpt-4',+ payload: instructionWithParent.payload,+ provider: 'openai',+ state,+ });+ expect(executeTurn).toHaveBeenCalledWith({assistantMessage: { id: 'assistant-1' },- instruction: instructionWithParent,+ context: contextOutput,model: 'gpt-4',provider: 'openai',state,@@ -148,11 +175,11 @@ describe('callLlm executor', () => {events: [],newState: state,};- const executeCall = vi.fn().mockResolvedValue(expected);+ const executeTurn = vi.fn().mockResolvedValue(expected);const messages = createMessageTransport();const host = createHost({- executeCall,+ executeTurn,stream: vi.fn(),},messages,@@ -167,30 +194,51 @@ describe('callLlm executor', () => {await expect(callLlm(host)(reuseInstruction, state)).resolves.toBe(expected);expect(messages.createAssistantMessage).not.toHaveBeenCalled();- expect(executeCall).toHaveBeenCalledWith(+ expect(executeTurn).toHaveBeenCalledWith(expect.objectContaining({assistantMessage: { id: 'assistant-existing' },}),);});- it('throws when the LLM transport does not provide executeCall', async () => {+ it('throws when the LLM transport does not provide executeTurn', async () => {const host = createHost({stream: vi.fn(),});await expect(callLlm(host)(instruction, createState())).rejects.toThrow(- 'LLMTransport.executeCall is required for call_llm executor',+ 'LLMTransport.executeTurn is required for call_llm executor',);});+ it('publishes context build failures without executing the model turn', async () => {+ const error = new Error('context failed');+ const context: ContextBuilder = { build: vi.fn().mockRejectedValue(error) };+ const executeTurn = vi.fn();+ const stream = createStreamSink();+ const host = createHost(+ { executeTurn, stream: vi.fn() },+ createMessageTransport(),+ stream,+ context,+ );++ await expect(callLlm(host)(instruction, createState())).rejects.toBe(error);+ expect(stream.publishError).toHaveBeenCalledWith({+ error,+ phase: 'llm_execution',+ stepIndex: 0,+ });+ expect(executeTurn).not.toHaveBeenCalled();+ });+it('fails before creating an assistant message when the parent message is missing', async () => {const messages = createMessageTransport();vi.mocked(messages.findById).mockResolvedValue(undefined);const stream = createStreamSink();const host = createHost({- executeCall: vi.fn(),+ executeTurn: vi.fn(),stream: vi.fn(),},messages,diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.tsindex b2e03089f80..477dee533e7 100644--- a/packages/agent-runtime/src/executors/callLlm.ts+++ b/packages/agent-runtime/src/executors/callLlm.ts@@ -1,20 +1,28 @@-import type { AgentRuntimeHost, LLMCallExecuteInput } from '../transport';+import type { AgentRuntimeHost, LLMTurnInput } from '../transport';import type { AgentInstruction, CallLLMPayload, InstructionExecutor } from '../types';const CONVERSATION_PARENT_MISSING_ERROR_TYPE = 'ConversationParentMissing';interface LLMCallTransport {- executeCall: (input: LLMCallExecuteInput) => ReturnType<InstructionExecutor>;+ executeTurn: (input: LLMTurnInput) => ReturnType<InstructionExecutor>;}const requireLLMCallTransport = (host: AgentRuntimeHost) => {const llm = host.transports.llm;- if (!llm?.executeCall) {- throw new Error('LLMTransport.executeCall is required for call_llm executor');+ if (!llm?.executeTurn) {+ throw new Error('LLMTransport.executeTurn is required for call_llm executor');}return llm as NonNullable<AgentRuntimeHost['transports']['llm']> & LLMCallTransport;};+const requireContextBuilder = (host: AgentRuntimeHost) => {+ const context = host.transports.context;+ if (!context) {+ throw new Error('ContextBuilder is required for call_llm executor');+ }+ return context;+};+const createConversationParentMissingError = (parentId: string) => {const error = new Error(`Conversation parent message ${parentId} no longer exists. It was likely deleted while the operation was running.`,@@ -65,17 +73,18 @@ const buildAssistantMessageSeed = (});/**- * `call_llm` executor — transitional transport-backed entry point.+ * Package-owned `call_llm` executor entry point.** The server-specific implementation still lives behind the LLM transport while- * the remaining context/stream/persist internals are broken into package-owned- * ports. This removes the direct server executor registration first, matching- * the migration shape used by the other runtime executors.+ * the remaining context/stream/persist internals are broken into narrower+ * package-owned ports. The transport executes a prepared turn rather than+ * masquerading as another instruction executor.*/export const callLlm =(host: AgentRuntimeHost): InstructionExecutor =>async (instruction, state) => {const { operation, transports } = host;+ const contextBuilder = requireContextBuilder(host);const llm = requireLLMCallTransport(host);const { payload } = instruction as Extract<AgentInstruction, { type: 'call_llm' }>;const llmPayload = payload as CallLLMPayload & {@@ -134,9 +143,25 @@ export const callLlm =type: 'stream_start',});- return llm.executeCall({+ const context = await contextBuilder+ .build({+ model,+ payload: llmPayload,+ provider,+ state,+ })+ .catch(async (error) => {+ await transports.stream.publishError?.({+ error,+ phase: 'llm_execution',+ stepIndex: operation.stepIndex,+ });+ throw error;+ });++ return llm.executeTurn({assistantMessage,- instruction: instruction as Extract<AgentInstruction, { type: 'call_llm' }>,+ context,model,provider,state,diff --git a/packages/agent-runtime/src/transport/context.ts b/packages/agent-runtime/src/transport/context.tsindex 7214c1266a8..d452282641e 100644--- a/packages/agent-runtime/src/transport/context.ts+++ b/packages/agent-runtime/src/transport/context.ts@@ -1,23 +1,29 @@-import type { OpenAIChatMessage, UIChatMessage } from '@lobechat/types';+import type { ResolvedToolSet } from '@lobechat/context-engine';++import type { AgentState, CallLLMPayload } from '../types';/*** Inputs for building the final prompt sent to the model.*- * NOTE (scaffolding): only the always-required trio is pinned. The many context- * sources the server engine consumes (systemRole, knowledge, tool manifests,- * agentDocuments, persona/onboarding, topic references, capabilities…) are- * resolved/bound by the adapter and firm when `call_llm` / `compress_context`- * (Tier C) migrate onto the port.+ * The package passes the runtime-owned payload/state while adapters bind host+ * sources such as knowledge, skills, documents, persona, and topic references.*/export interface ContextBuildInput {[key: string]: unknown;- messages: UIChatMessage[];model: string;+ payload: CallLLMPayload;provider: string;+ state: AgentState;}export interface ContextBuildOutput {- messages: OpenAIChatMessage[];+ /** Adapter-native prepared messages; kept in-memory and out of serialized state. */+ messages: unknown[];+ /** Adapter-native model extension parameters consumed by the LLM transport. */+ modelParameters?: unknown;+ preserveThinking?: boolean;+ replayAssistantReasoning: boolean;+ resolvedTools?: ResolvedToolSet;}/**diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.tsindex 3fd7b0c3261..39be28eda9f 100644--- a/packages/agent-runtime/src/transport/llm.ts+++ b/packages/agent-runtime/src/transport/llm.ts@@ -1,11 +1,7 @@import type { ModelUsage, OpenAIChatMessage } from '@lobechat/types';-import type {- AgentInstructionCallLlm,- AgentState,- CallLLMPayload,- InstructionExecutor,-} from '../types';+import type { AgentState, CallLLMPayload, InstructionExecutionResult } from '../types';+import type { ContextBuildOutput } from './context';import type { RuntimeMessageRef } from './message';export interface LLMStreamPayload {@@ -38,9 +34,9 @@ export interface LLMStreamHandlers {onText?: (text: string) => void;}-export interface LLMCallExecuteInput {+export interface LLMTurnInput {assistantMessage: RuntimeMessageRef;- instruction: AgentInstructionCallLlm;+ context: ContextBuildOutput;model: string;provider: string;state: AgentState;@@ -58,12 +54,11 @@ export interface LLMCallExecuteInput {*/export interface LLMTransport {/**- * Executes a full agent `call_llm` instruction. This is a transitional port:- * the server adapter can keep provider/context/persistence specifics while- * the package owns the executor registration point. The internals are split- * into smaller context/stream/persist ports in the next migration slices.+ * Executes one prepared model turn. The package executor owns instruction+ * setup while the adapter owns host-specific context, retry, and persistence+ * until those phases move onto narrower transport ports.*/- executeCall?: (input: LLMCallExecuteInput) => ReturnType<InstructionExecutor>;+ executeTurn?: (input: LLMTurnInput) => Promise<InstructionExecutionResult>;stream: (payload: LLMStreamPayload,handlers?: LLMStreamHandlers,diff --git a/packages/agent-runtime/src/types/runtime.ts b/packages/agent-runtime/src/types/runtime.tsindex 675d848bf00..fdaabd5335b 100644--- a/packages/agent-runtime/src/types/runtime.ts+++ b/packages/agent-runtime/src/types/runtime.ts@@ -2,6 +2,13 @@ import type { AgentEvent } from './event';import type { AgentInstruction, AgentRuntimeContext } from './instruction';import type { AgentState } from './state';+export interface InstructionExecutionResult {+ events: AgentEvent[];+ newState: AgentState;+ /** Next context to pass to Agent runner (if execution should continue) */+ nextContext?: AgentRuntimeContext;+}+export type InstructionExecutor = (instruction: AgentInstruction,state: AgentState,@@ -10,12 +17,7 @@ export type InstructionExecutor = (* Contains stepContext with dynamic state like lobe-agent todos*/context?: AgentRuntimeContext,-) => Promise<{- events: AgentEvent[];- newState: AgentState;- /** Next context to pass to Agent runner (if execution should continue) */- nextContext?: AgentRuntimeContext;-}>;+) => Promise<InstructionExecutionResult>;export interface RuntimeConfig {/** Custom executors for specific instruction types */