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: remove legacy LLM turn executor (#17089)

Arvin Xu9331c9c96502
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
index 9e9972cfb91..8032d9f56fe 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
@@ -2,23 +2,43 @@ import type {
BlobStore,
LLMAttemptExecution,
LLMAttemptInput,
+ LLMAttemptOutput,
+ LLMCallErrorInput,
+ LLMRetryInput,
+ LLMRetryPolicy,
LLMStreamPayload,
LLMStreamResult,
+ LLMTrace,
+ LLMTraceInput,
LLMTransport,
- LLMTurnInput,
- LLMTurnSession,
} from '@lobechat/agent-runtime';
+import { resolveLLMMaxAttempts, resolveLLMRetryBudget } from '@lobechat/agent-runtime';
+import { BRANDING_PROVIDER } from '@lobechat/business-const';
import {
type ChatStreamPayload,
consumeStreamUntilDone,
+ ModelEmptyError,
type ModelRuntime,
} from '@lobechat/model-runtime';
+import {
+ context as otelContext,
+ SpanKind,
+ SpanStatusCode,
+ trace as otelTrace,
+} from '@lobechat/observability-otel/api';
+import {
+ buildChatRequestAttributes,
+ buildChatResponseAttributes,
+ chatSpanName,
+ tracer as agentRuntimeTracer,
+} from '@lobechat/observability-otel/modules/agent-runtime';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import type { RuntimeExecutorContext } from '../context';
+import { log, sleep } from '../executorHelpers';
+import { classifyLLMError } from '../llmErrorClassification';
import { createServerCallLlmAttempt } from './serverCallLlmAttempt';
-import { openServerCallLlmTurn } from './serverCallLlmExecutor';
const getErrorMessage = (error: unknown): string => {
if (error instanceof Error && error.message) return error.message;
@@ -30,34 +50,152 @@ const getErrorMessage = (error: unknown): string => {
return JSON.stringify(error);
};
+const SERVER_LLM_RETRY_POLICY = {
+ isEmptyCompletionError: (error: unknown) => error instanceof ModelEmptyError,
+ noRetryProviders: [BRANDING_PROVIDER],
+};
+
+class ServerLLMRetryPolicy implements LLMRetryPolicy {
+ constructor(private readonly ctx: RuntimeExecutorContext) {}
+
+ classifyError(error: unknown) {
+ return classifyLLMError(error);
+ }
+
+ maxAttempts(provider: string) {
+ return resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY);
+ }
+
+ onError({ error, events, retryBudget }: LLMCallErrorInput) {
+ if (error instanceof ModelEmptyError && error.diagnostics) {
+ error.diagnostics.retryBudget = retryBudget;
+ error.diagnostics.retryEvents = events
+ .filter((event) => event.type === 'stream_retry')
+ .map((event) => event.data);
+ }
+
+ console.error(
+ `[StreamingLLMExecutor][${this.ctx.operationId}:${this.ctx.stepIndex}] LLM execution failed:`,
+ error,
+ );
+ }
+
+ onRetry({ attempt, delayMs, error, maxAttempts }: LLMRetryInput) {
+ log(
+ '[%s:%d] LLM call failed with kind=%s (attempt %d/%d), retrying in %dms ...',
+ this.ctx.operationId,
+ this.ctx.stepIndex,
+ error.kind,
+ attempt,
+ maxAttempts,
+ delayMs,
+ );
+ }
+
+ resolveRetryBudget(provider: string, error: unknown) {
+ return resolveLLMRetryBudget(provider, error, SERVER_LLM_RETRY_POLICY);
+ }
+
+ async waitForRetry(delayMs: number): Promise<void> {
+ await sleep(delayMs);
+ }
+}
+
+class ServerLLMTrace implements LLMTrace {
+ private readonly chatContext: ReturnType<typeof otelTrace.setSpan>;
+ private readonly chatSpan: ReturnType<typeof agentRuntimeTracer.startSpan>;
+ private firstChunkAt?: number;
+ private readonly llmStartTime = Date.now();
+ private readonly operationLogId: string;
+
+ constructor(
+ private readonly ctx: RuntimeExecutorContext,
+ input: LLMTraceInput,
+ ) {
+ this.operationLogId = `${ctx.operationId}:${ctx.stepIndex}`;
+ log(
+ '[%s][call_llm] Starting operation with prepared assistant message: %s',
+ this.operationLogId,
+ input.assistantMessageId,
+ );
+
+ this.chatSpan = agentRuntimeTracer.startSpan(chatSpanName(input.model), {
+ attributes: buildChatRequestAttributes({
+ conversationId: input.conversationId,
+ operationId: ctx.operationId,
+ provider: input.provider,
+ requestModel: input.model,
+ stepIndex: ctx.stepIndex,
+ stream: ctx.stream ?? true,
+ }),
+ kind: SpanKind.CLIENT,
+ });
+ this.chatContext = otelTrace.setSpan(otelContext.active(), this.chatSpan);
+ }
+
+ close(error?: unknown) {
+ if (error) {
+ this.chatSpan.recordException(error as Error);
+ this.chatSpan.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
+ this.chatSpan.end();
+ }
+
+ onFirstChunk() {
+ if (this.firstChunkAt === undefined) {
+ this.firstChunkAt = Date.now() - this.llmStartTime;
+ }
+ }
+
+ recordResult(output: LLMAttemptOutput) {
+ return this.run(async () => {
+ log('[%s] call_llm completed', this.operationLogId);
+ this.chatSpan.setAttributes(
+ buildChatResponseAttributes({
+ cacheReadInputTokens: output.usage?.inputCachedTokens,
+ finishReasons: output.finishReason ? [output.finishReason] : undefined,
+ inputTokens: output.usage?.totalInputTokens,
+ outputTokens: output.usage?.totalOutputTokens,
+ reasoningOutputTokens: output.usage?.outputReasoningTokens,
+ timeToFirstChunkMs: this.firstChunkAt,
+ }),
+ );
+ });
+ }
+
+ run<T>(task: () => Promise<T>): Promise<T> {
+ return otelContext.with(this.chatContext, task);
+ }
+}
+
/**
* Server {@link LLMTransport} adapter — wraps model-runtime streaming and
* returns the aggregated content/usage that package executors need.
*/
export class ServerLLMTransport implements LLMTransport {
+ readonly retryPolicy: LLMRetryPolicy;
+
+ private readonly modelRuntimePromises = new Map<
+ string,
+ ReturnType<ServerLLMTransport['createModelRuntime']>
+ >();
+
constructor(
private readonly ctx: RuntimeExecutorContext,
private readonly blobStore?: BlobStore,
- ) {}
-
- openTurn(input: LLMTurnInput): LLMTurnSession {
- let modelRuntimePromise: ReturnType<ServerLLMTransport['createModelRuntime']> | undefined;
+ ) {
+ this.retryPolicy = new ServerLLMRetryPolicy(ctx);
+ }
- return openServerCallLlmTurn(this.ctx, {
- assistantMessage: input.assistantMessage,
- context: input.context,
- model: input.model,
- provider: input.provider,
- runAttempt: async (attemptInput) => {
- modelRuntimePromise ??= this.createModelRuntime(input.provider);
- return this.runAttemptWithRuntime(attemptInput, await modelRuntimePromise);
- },
- state: input.state,
- });
+ createTrace(input: LLMTraceInput): LLMTrace {
+ return new ServerLLMTrace(this.ctx, input);
}
async runAttempt(input: LLMAttemptInput): Promise<LLMAttemptExecution> {
- const modelRuntime = await this.createModelRuntime(input.provider);
+ const modelRuntime = await this.getModelRuntime(input.provider);
return this.runAttemptWithRuntime(input, modelRuntime);
}
@@ -108,6 +246,15 @@ export class ServerLLMTransport implements LLMTransport {
);
}
+ private getModelRuntime(provider: string) {
+ let promise = this.modelRuntimePromises.get(provider);
+ if (!promise) {
+ promise = this.createModelRuntime(provider);
+ this.modelRuntimePromises.set(provider, promise);
+ }
+ return promise;
+ }
+
private async runAttemptWithRuntime(
input: LLMAttemptInput,
modelRuntime: Pick<ModelRuntime, 'chat'>,
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
deleted file mode 100644
index 0b7479f9a95..00000000000
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-import {
- type AgentState,
- type ContextBuildOutput,
- type LLMAttemptOutput,
- type LLMTransport,
- type LLMTurnAttemptInput,
- type LLMTurnErrorInput,
- type LLMTurnRetryInput,
- type LLMTurnSession,
- resolveLLMMaxAttempts,
- resolveLLMRetryBudget,
-} from '@lobechat/agent-runtime';
-import { BRANDING_PROVIDER } from '@lobechat/business-const';
-import { ModelEmptyError } from '@lobechat/model-runtime';
-import {
- context as otelContext,
- SpanKind,
- SpanStatusCode,
- trace as otelTrace,
-} from '@lobechat/observability-otel/api';
-import {
- buildChatRequestAttributes,
- buildChatResponseAttributes,
- chatSpanName,
- tracer as agentRuntimeTracer,
-} from '@lobechat/observability-otel/modules/agent-runtime';
-
-import { type RuntimeExecutorContext } from '../context';
-import { log, sleep } from '../executorHelpers';
-import { classifyLLMError } from '../llmErrorClassification';
-
-interface ServerCallLlmExecutionContext {
- assistantMessage: { id: string };
- context: ContextBuildOutput;
- model: string;
- provider: string;
- runAttempt: NonNullable<LLMTransport['runAttempt']>;
- state: AgentState;
-}
-
-const SERVER_LLM_RETRY_POLICY = {
- isEmptyCompletionError: (error: unknown) => error instanceof ModelEmptyError,
- noRetryProviders: [BRANDING_PROVIDER],
-};
-
-class ServerCallLlmTurnSession implements LLMTurnSession {
- readonly maxAttempts: number;
-
- private readonly chatContext: ReturnType<typeof otelTrace.setSpan>;
- private readonly chatSpan: ReturnType<typeof agentRuntimeTracer.startSpan>;
- private firstChunkAt?: number;
- private readonly llmStartTime = Date.now();
- private readonly operationLogId: string;
-
- constructor(
- private readonly ctx: RuntimeExecutorContext,
- private readonly prepared: ServerCallLlmExecutionContext,
- ) {
- const { context, model, provider, state } = prepared;
- const processedMessages = context.messages as Array<{ role?: string }>;
-
- if (!context.resolvedTools) {
- throw new Error('Resolved tools are required for a server LLM turn');
- }
- if (!processedMessages.some((message) => message.role !== 'system')) {
- throw new Error(
- `call_llm produced no non-system messages for ${provider}/${model} ` +
- `(topic=${state.metadata?.topicId ?? 'n/a'}, step=${ctx.stepIndex}); refusing to dispatch`,
- );
- }
-
- this.operationLogId = `${ctx.operationId}:${ctx.stepIndex}`;
- this.maxAttempts = resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY);
- log(
- '[%s][call_llm] Starting operation with prepared assistant message: %s',
- this.operationLogId,
- prepared.assistantMessage.id,
- );
-
- this.chatSpan = agentRuntimeTracer.startSpan(chatSpanName(model), {
- attributes: buildChatRequestAttributes({
- conversationId: state.metadata?.topicId,
- operationId: ctx.operationId,
- provider,
- requestModel: model,
- stepIndex: ctx.stepIndex,
- stream: ctx.stream ?? true,
- }),
- kind: SpanKind.CLIENT,
- });
- this.chatContext = otelTrace.setSpan(otelContext.active(), this.chatSpan);
- }
-
- classifyError(error: unknown) {
- return classifyLLMError(error);
- }
-
- close(error?: unknown) {
- if (error) {
- this.chatSpan.recordException(error as Error);
- this.chatSpan.setStatus({
- code: SpanStatusCode.ERROR,
- message: error instanceof Error ? error.message : String(error),
- });
- }
- this.chatSpan.end();
- }
-
- async handleError({ error, events, retryBudget }: LLMTurnErrorInput) {
- await otelContext.with(this.chatContext, async () => {
- if (error instanceof ModelEmptyError && error.diagnostics) {
- error.diagnostics.retryBudget = retryBudget;
- error.diagnostics.retryEvents = events
- .filter((event) => event.type === 'stream_retry')
- .map((event) => event.data);
- }
-
- console.error(
- `[StreamingLLMExecutor][${this.ctx.operationId}:${this.ctx.stepIndex}] LLM execution failed:`,
- error,
- );
- });
- }
-
- resolveRetryBudget(error: unknown) {
- return resolveLLMRetryBudget(this.prepared.provider, error, SERVER_LLM_RETRY_POLICY);
- }
-
- onRetry({ attempt, delayMs, error, maxAttempts }: LLMTurnRetryInput) {
- log(
- '[%s] LLM call failed with kind=%s (attempt %d/%d), retrying in %dms ...',
- this.operationLogId,
- error.kind,
- attempt,
- maxAttempts,
- delayMs,
- );
- }
-
- recordResult(output: LLMAttemptOutput) {
- return otelContext.with(this.chatContext, () => {
- log('[%s] call_llm completed', this.operationLogId);
- this.chatSpan.setAttributes(
- buildChatResponseAttributes({
- cacheReadInputTokens: output.usage?.inputCachedTokens,
- finishReasons: output.finishReason ? [output.finishReason] : undefined,
- inputTokens: output.usage?.totalInputTokens,
- outputTokens: output.usage?.totalOutputTokens,
- reasoningOutputTokens: output.usage?.outputReasoningTokens,
- timeToFirstChunkMs: this.firstChunkAt,
- }),
- );
- });
- }
-
- runAttempt({ attempt, events }: LLMTurnAttemptInput) {
- return otelContext.with(this.chatContext, () =>
- this.prepared.runAttempt({
- attempt,
- context: this.prepared.context,
- events,
- maxAttempts: this.maxAttempts,
- model: this.prepared.model,
- onFirstChunk: () => {
- if (this.firstChunkAt === undefined) {
- this.firstChunkAt = Date.now() - this.llmStartTime;
- }
- },
- provider: this.prepared.provider,
- state: this.prepared.state,
- }),
- );
- }
-
- async waitForRetry(delayMs: number): Promise<void> {
- await sleep(delayMs);
- }
-}
-
-export const openServerCallLlmTurn = (
- ctx: RuntimeExecutorContext,
- prepared: ServerCallLlmExecutionContext,
-): LLMTurnSession => new ServerCallLlmTurnSession(ctx, prepared);
diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.ts
index 83502266c5d..5da011c3460 100644
--- a/packages/agent-runtime/src/executors/callLlm.test.ts
+++ b/packages/agent-runtime/src/executors/callLlm.test.ts
@@ -5,8 +5,9 @@ import type {
ContextBuilder,
ContextBuildOutput,
LLMAttemptOutput,
+ LLMRetryPolicy,
+ LLMTrace,
LLMTransport,
- LLMTurnSession,
MessageTransport,
OperationStore,
StreamSink,
@@ -84,6 +85,13 @@ const createStreamSink = (): StreamSink => ({
const contextOutput: ContextBuildOutput = {
messages: [{ content: 'prepared hello', role: 'user' }],
replayAssistantReasoning: false,
+ resolvedTools: {
+ enabledToolIds: [],
+ manifestMap: {},
+ promptManifestMap: {},
+ sourceMap: {},
+ tools: [],
+ },
};
const createContextBuilder = (): ContextBuilder => ({
@@ -104,18 +112,43 @@ const createAttemptOutput = (content = 'answer'): LLMAttemptOutput => ({
toolsCalling: [],
});
-const createTurnSession = (overrides: Partial<LLMTurnSession> = {}): LLMTurnSession => ({
+const createRetryPolicy = (overrides: Partial<LLMRetryPolicy> = {}): LLMRetryPolicy => ({
classifyError: vi.fn().mockReturnValue({ kind: 'stop', message: 'failed' }),
- close: vi.fn(),
- handleError: vi.fn().mockResolvedValue(undefined),
- maxAttempts: 3,
- recordResult: vi.fn(),
+ maxAttempts: vi.fn().mockReturnValue(3),
+ onError: vi.fn().mockResolvedValue(undefined),
resolveRetryBudget: vi.fn().mockReturnValue(2),
- runAttempt: vi.fn().mockResolvedValue({ ok: true, output: createAttemptOutput() }),
waitForRetry: vi.fn().mockResolvedValue(undefined),
...overrides,
});
+const createTrace = (overrides: Partial<LLMTrace> = {}): LLMTrace => ({
+ close: vi.fn(),
+ onFirstChunk: vi.fn(),
+ recordResult: vi.fn(),
+ run: vi.fn((task) => task()),
+ ...overrides,
+});
+
+const createCallTransport = ({
+ policy = createRetryPolicy(),
+ runAttempt = vi.fn().mockResolvedValue({ ok: true, output: createAttemptOutput() }),
+ trace = createTrace(),
+}: {
+ policy?: LLMRetryPolicy;
+ runAttempt?: ReturnType<typeof vi.fn>;
+ trace?: LLMTrace;
+} = {}) => {
+ const createTraceScope = vi.fn().mockReturnValue(trace);
+ const llm: LLMTransport = {
+ createTrace: createTraceScope,
+ retryPolicy: policy,
+ runAttempt,
+ stream: vi.fn(),
+ };
+
+ return { createTrace: createTraceScope, llm, policy, runAttempt, trace };
+};
+
const createHost = (
llm: LLMTransport,
messages = createMessageTransport(),
@@ -136,20 +169,11 @@ const createHost = (
describe('callLlm executor', () => {
it('prepares the assistant message and delegates call_llm execution to the LLM transport', async () => {
const state = createState();
- const session = createTurnSession();
- const openTurn = vi.fn().mockReturnValue(session);
+ const transport = createCallTransport();
const messages = createMessageTransport();
const stream = createStreamSink();
const context = createContextBuilder();
- const host = createHost(
- {
- openTurn,
- stream: vi.fn(),
- },
- messages,
- stream,
- context,
- );
+ const host = createHost(transport.llm, messages, stream, context);
const instructionWithParent: AgentInstructionCallLlm = {
payload: {
...instruction.payload,
@@ -187,18 +211,23 @@ describe('callLlm executor', () => {
provider: 'openai',
state,
});
- expect(openTurn).toHaveBeenCalledWith({
- assistantMessage: { id: 'assistant-1' },
- context: contextOutput,
+ expect(transport.createTrace).toHaveBeenCalledWith({
+ assistantMessageId: 'assistant-1',
+ conversationId: 'topic-1',
model: 'gpt-4',
provider: 'openai',
- state,
- stepLabel: undefined,
- });
- expect(session.runAttempt).toHaveBeenCalledWith({
- attempt: 1,
- events: [expect.objectContaining({ type: 'llm_result' })],
});
+ expect(transport.runAttempt).toHaveBeenCalledWith(
+ expect.objectContaining({
+ attempt: 1,
+ context: contextOutput,
+ events: [expect.objectContaining({ type: 'llm_result' })],
+ maxAttempts: 3,
+ model: 'gpt-4',
+ provider: 'openai',
+ state,
+ }),
+ );
expect(messages.update).toHaveBeenCalledWith(
'assistant-1',
expect.objectContaining({ content: 'answer', search: null }),
@@ -208,22 +237,15 @@ describe('callLlm executor', () => {
id: 'assistant-1',
role: 'assistant',
});
- expect(session.recordResult).toHaveBeenCalledWith(createAttemptOutput());
- expect(session.close).toHaveBeenCalledWith(undefined);
+ expect(transport.trace.recordResult).toHaveBeenCalledWith(createAttemptOutput());
+ expect(transport.trace.close).toHaveBeenCalledWith(undefined);
});
it('reuses an existing assistant message without creating a new one', async () => {
const state = createState();
- const session = createTurnSession();
- const openTurn = vi.fn().mockReturnValue(session);
+ const transport = createCallTransport();
const messages = createMessageTransport();
- const host = createHost(
- {
- openTurn,
- stream: vi.fn(),
- },
- messages,
- );
+ const host = createHost(transport.llm, messages);
const reuseInstruction: AgentInstructionCallLlm = {
payload: {
...instruction.payload,
@@ -236,34 +258,50 @@ describe('callLlm executor', () => {
newState: { messages: [expect.objectContaining({ id: 'assistant-existing' })] },
});
expect(messages.createAssistantMessage).not.toHaveBeenCalled();
- expect(openTurn).toHaveBeenCalledWith(
+ expect(transport.createTrace).toHaveBeenCalledWith(
expect.objectContaining({
- assistantMessage: { id: 'assistant-existing' },
+ assistantMessageId: 'assistant-existing',
}),
);
});
- it('throws when the LLM transport does not provide openTurn', async () => {
+ it('throws when the LLM transport does not provide runAttempt', async () => {
const host = createHost({
+ retryPolicy: createRetryPolicy(),
stream: vi.fn(),
});
await expect(callLlm(host)(instruction, createState())).rejects.toThrow(
- 'LLMTransport.openTurn is required for call_llm executor',
+ 'LLMTransport.runAttempt is required for call_llm executor',
+ );
+ });
+
+ it('throws when the LLM transport does not provide retryPolicy', async () => {
+ const host = createHost({ runAttempt: vi.fn(), stream: vi.fn() });
+
+ await expect(callLlm(host)(instruction, createState())).rejects.toThrow(
+ 'LLMTransport.retryPolicy is required for call_llm executor',
);
});
+ it('executes without an optional tracing adapter', async () => {
+ const transport = createCallTransport();
+ delete transport.llm.createTrace;
+
+ await expect(
+ callLlm(createHost(transport.llm))(instruction, createState()),
+ ).resolves.toMatchObject({
+ newState: { messages: [expect.objectContaining({ content: 'answer' })] },
+ });
+ expect(transport.runAttempt).toHaveBeenCalledTimes(1);
+ });
+
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 openTurn = vi.fn();
+ const transport = createCallTransport();
const stream = createStreamSink();
- const host = createHost(
- { openTurn, stream: vi.fn() },
- createMessageTransport(),
- stream,
- context,
- );
+ const host = createHost(transport.llm, createMessageTransport(), stream, context);
await expect(callLlm(host)(instruction, createState())).rejects.toBe(error);
expect(stream.publishError).toHaveBeenCalledWith({
@@ -271,21 +309,47 @@ describe('callLlm executor', () => {
phase: 'llm_execution',
stepIndex: 0,
});
- expect(openTurn).not.toHaveBeenCalled();
+ expect(transport.runAttempt).not.toHaveBeenCalled();
+ });
+
+ it('rejects prepared context without resolved tools before creating a trace', async () => {
+ const transport = createCallTransport();
+ const context: ContextBuilder = {
+ build: vi.fn().mockResolvedValue({
+ ...contextOutput,
+ resolvedTools: undefined,
+ }),
+ };
+
+ await expect(
+ callLlm(createHost(transport.llm, undefined, undefined, context))(instruction, createState()),
+ ).rejects.toThrow('Resolved tools are required for call_llm');
+ expect(transport.createTrace).not.toHaveBeenCalled();
+ expect(transport.runAttempt).not.toHaveBeenCalled();
+ });
+
+ it('rejects prepared context containing only system messages', async () => {
+ const transport = createCallTransport();
+ const context: ContextBuilder = {
+ build: vi.fn().mockResolvedValue({
+ ...contextOutput,
+ messages: [{ content: 'system only', role: 'system' }],
+ }),
+ };
+
+ await expect(
+ callLlm(createHost(transport.llm, undefined, undefined, context))(instruction, createState()),
+ ).rejects.toThrow('call_llm produced no non-system messages for openai/gpt-4');
+ expect(transport.createTrace).not.toHaveBeenCalled();
+ expect(transport.runAttempt).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(
- {
- openTurn: vi.fn(),
- stream: vi.fn(),
- },
- messages,
- stream,
- );
+ const transport = createCallTransport();
+ const host = createHost(transport.llm, messages, stream);
const instructionWithParent: AgentInstructionCallLlm = {
payload: {
...instruction.payload,
@@ -321,22 +385,22 @@ describe('callLlm executor', () => {
.mockResolvedValueOnce({ error, ok: false, output: firstOutput })
.mockResolvedValueOnce({ ok: true, output: finalOutput });
const onRetry = vi.fn();
- const session = createTurnSession({
+ const policy = createRetryPolicy({
classifyError: vi.fn().mockReturnValue({
code: 'UPSTREAM_TIMEOUT',
kind: 'retry',
message: error.message,
}),
onRetry,
- runAttempt,
});
+ const transport = createCallTransport({ policy, runAttempt });
const stream = createStreamSink();
const operationStore: OperationStore = {
clearRunningMark: vi.fn(),
loadState: vi.fn().mockResolvedValue(null),
};
const host = createHost(
- { openTurn: vi.fn().mockReturnValue(session), stream: vi.fn() },
+ transport.llm,
createMessageTransport(),
stream,
createContextBuilder(),
@@ -355,14 +419,22 @@ describe('callLlm executor', () => {
},
type: 'stream_retry' as const,
};
- expect(runAttempt).toHaveBeenNthCalledWith(1, {
- attempt: 1,
- events: [retryEvent, expect.objectContaining({ type: 'llm_result' })],
- });
- expect(runAttempt).toHaveBeenNthCalledWith(2, {
- attempt: 2,
- events: [retryEvent, expect.objectContaining({ type: 'llm_result' })],
- });
+ expect(runAttempt).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ attempt: 1,
+ events: [retryEvent, expect.objectContaining({ type: 'llm_result' })],
+ maxAttempts: 3,
+ }),
+ );
+ expect(runAttempt).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ attempt: 2,
+ events: [retryEvent, expect.objectContaining({ type: 'llm_result' })],
+ maxAttempts: 3,
+ }),
+ );
expect(onRetry).toHaveBeenCalledWith({
attempt: 1,
delayMs: 1000,
@@ -378,21 +450,22 @@ describe('callLlm executor', () => {
stepIndex: 0,
type: 'stream_retry',
});
- expect(session.waitForRetry).toHaveBeenCalledWith(1000);
+ expect(policy.waitForRetry).toHaveBeenCalledWith(1000);
expect(result.newState.messages.at(-1)).toMatchObject({ content: 'complete' });
- expect(session.recordResult).toHaveBeenCalledWith(finalOutput);
- expect(session.handleError).not.toHaveBeenCalled();
- expect(session.close).toHaveBeenCalledWith(undefined);
+ expect(transport.trace.recordResult).toHaveBeenCalledWith(finalOutput);
+ expect(policy.onError).not.toHaveBeenCalled();
+ expect(transport.trace.close).toHaveBeenCalledWith(undefined);
});
it('stops retrying and persists the partial attempt when the operation is interrupted', async () => {
const state = createState();
const error = new Error('stream aborted');
const output = createAttemptOutput('partial');
- const session = createTurnSession({
+ const policy = createRetryPolicy({
classifyError: vi.fn().mockReturnValue({ kind: 'retry', message: error.message }),
- runAttempt: vi.fn().mockResolvedValue({ error, ok: false, output }),
});
+ const runAttempt = vi.fn().mockResolvedValue({ error, ok: false, output });
+ const transport = createCallTransport({ policy, runAttempt });
const operationStore: OperationStore = {
clearRunningMark: vi.fn(),
loadState: vi.fn().mockResolvedValue({ ...state, status: 'interrupted' }),
@@ -400,7 +473,7 @@ describe('callLlm executor', () => {
const stream = createStreamSink();
const messages = createMessageTransport();
const host = createHost(
- { openTurn: vi.fn().mockReturnValue(session), stream: vi.fn() },
+ transport.llm,
messages,
stream,
createContextBuilder(),
@@ -409,8 +482,8 @@ describe('callLlm executor', () => {
await expect(callLlm(host)(instruction, state)).rejects.toBe(error);
- expect(session.runAttempt).toHaveBeenCalledTimes(1);
- expect(session.waitForRetry).not.toHaveBeenCalled();
+ expect(runAttempt).toHaveBeenCalledTimes(1);
+ expect(policy.waitForRetry).not.toHaveBeenCalled();
expect(messages.update).toHaveBeenCalledWith(
'assistant-1',
expect.objectContaining({
@@ -418,14 +491,14 @@ describe('callLlm executor', () => {
metadata: expect.objectContaining({ interruptedMidStream: true }),
}),
);
- expect(session.handleError).toHaveBeenCalledWith({
+ expect(policy.onError).toHaveBeenCalledWith({
error,
events: [],
interrupted: true,
output,
retryBudget: 2,
});
- expect(session.close).toHaveBeenCalledWith(error);
+ expect(transport.trace.close).toHaveBeenCalledWith(error);
expect(stream.publishError).toHaveBeenCalledWith({
error,
phase: 'llm_execution',
diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.ts
index ddf4dad2335..51b96089c0e 100644
--- a/packages/agent-runtime/src/executors/callLlm.ts
+++ b/packages/agent-runtime/src/executors/callLlm.ts
@@ -1,23 +1,44 @@
import type {
AgentRuntimeHost,
+ ContextBuildOutput,
LLMAttemptOutput,
- LLMTurnInput,
- LLMTurnSession,
+ LLMRetryPolicy,
+ LLMTrace,
+ LLMTransport,
} from '../transport';
-import type { AgentEvent, AgentInstruction, CallLLMPayload, InstructionExecutor } from '../types';
+import type {
+ AgentEvent,
+ AgentInstruction,
+ AgentState,
+ CallLLMPayload,
+ InstructionExecutor,
+} from '../types';
import { getLLMRetryDelayMs, shouldRetryLLM } from '../utils/runtimeRetry';
import { finalizeCallLlmTurn, persistInterruptedCallLlmResult } from './callLlmFinalizer';
const CONVERSATION_PARENT_MISSING_ERROR_TYPE = 'ConversationParentMissing';
interface LLMCallTransport {
- openTurn: (input: LLMTurnInput) => Promise<LLMTurnSession> | LLMTurnSession;
+ retryPolicy: LLMRetryPolicy;
+ runAttempt: NonNullable<LLMTransport['runAttempt']>;
+}
+
+interface PreparedCallLlmInput {
+ assistantMessageId: string;
+ context: ContextBuildOutput;
+ model: string;
+ provider: string;
+ state: AgentState;
+ stepLabel?: string;
}
const requireLLMCallTransport = (host: AgentRuntimeHost) => {
const llm = host.transports.llm;
- if (!llm?.openTurn) {
- throw new Error('LLMTransport.openTurn is required for call_llm executor');
+ if (!llm?.runAttempt) {
+ throw new Error('LLMTransport.runAttempt is required for call_llm executor');
+ }
+ if (!llm.retryPolicy) {
+ throw new Error('LLMTransport.retryPolicy is required for call_llm executor');
}
return llm as NonNullable<AgentRuntimeHost['transports']['llm']> & LLMCallTransport;
};
@@ -40,39 +61,56 @@ const isOperationInterrupted = async (host: AgentRuntimeHost) => {
}
};
-const executeTurnSession = async (
+const runWithTrace = <T>(trace: LLMTrace | undefined, task: () => Promise<T>) =>
+ trace ? trace.run(task) : task();
+
+const executePreparedCall = async (
host: AgentRuntimeHost,
- session: LLMTurnSession,
- turn: LLMTurnInput,
+ llm: LLMCallTransport,
+ prepared: PreparedCallLlmInput,
+ trace?: LLMTrace,
) => {
const events: AgentEvent[] = [];
+ const { retryPolicy } = llm;
+ const maxAttempts = retryPolicy.maxAttempts(prepared.provider);
let errorHandled = false;
let lastOutput: LLMAttemptOutput | undefined;
let terminalError: unknown;
try {
- for (let attempt = 1; attempt <= session.maxAttempts; attempt++) {
- const execution = await session.runAttempt({ attempt, events });
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ const execution = await runWithTrace(trace, () =>
+ llm.runAttempt({
+ attempt,
+ context: prepared.context,
+ events,
+ maxAttempts,
+ model: prepared.model,
+ onFirstChunk: trace?.onFirstChunk.bind(trace),
+ provider: prepared.provider,
+ state: prepared.state,
+ }),
+ );
lastOutput = execution.output;
if (execution.ok) {
return await finalizeCallLlmTurn({
- assistantMessageId: turn.assistantMessage.id,
+ assistantMessageId: prepared.assistantMessageId,
events,
host,
- model: turn.model,
+ model: prepared.model,
output: execution.output,
- provider: turn.provider,
- recordResult: session.recordResult?.bind(session),
- shouldReplayAssistantReasoning: turn.context.replayAssistantReasoning,
- state: turn.state,
- stepLabel: turn.stepLabel,
+ provider: prepared.provider,
+ recordResult: trace?.recordResult?.bind(trace),
+ shouldReplayAssistantReasoning: prepared.context.replayAssistantReasoning,
+ state: prepared.state,
+ stepLabel: prepared.stepLabel,
});
}
const { error } = execution;
- const classified = session.classifyError(error);
- const retryBudget = session.resolveRetryBudget(error);
+ const classified = retryPolicy.classifyError(error);
+ const retryBudget = retryPolicy.resolveRetryBudget(prepared.provider, error);
let interrupted = await isOperationInterrupted(host);
if (!interrupted && shouldRetryLLM(classified.kind, attempt, retryBudget)) {
@@ -83,24 +121,24 @@ const executeTurnSession = async (
delayMs,
errorType: classified.code,
kind: classified.kind,
- maxAttempts: session.maxAttempts,
+ maxAttempts,
},
type: 'stream_retry',
};
events.push(retryEvent);
- await session.onRetry?.({
+ await retryPolicy.onRetry?.({
attempt,
delayMs,
error: classified,
- maxAttempts: session.maxAttempts,
+ maxAttempts,
});
await host.transports.stream.publishEvent({
data: retryEvent.data,
stepIndex: host.operation.stepIndex,
type: 'stream_retry',
});
- await (session.waitForRetry ?? waitForRetry)(delayMs);
+ await (retryPolicy.waitForRetry ?? waitForRetry)(delayMs);
interrupted = await isOperationInterrupted(host);
if (!interrupted) continue;
@@ -109,17 +147,19 @@ const executeTurnSession = async (
errorHandled = true;
if (interrupted) {
await persistInterruptedCallLlmResult({
- assistantMessageId: turn.assistantMessage.id,
+ assistantMessageId: prepared.assistantMessageId,
host,
output: execution.output,
});
}
- await session.handleError({
- error,
- events,
- interrupted,
- output: execution.output,
- retryBudget,
+ await runWithTrace(trace, async () => {
+ await retryPolicy.onError?.({
+ error,
+ events,
+ interrupted,
+ output: execution.output,
+ retryBudget,
+ });
});
throw error;
}
@@ -131,21 +171,23 @@ const executeTurnSession = async (
const interrupted = await isOperationInterrupted(host);
if (interrupted && lastOutput) {
await persistInterruptedCallLlmResult({
- assistantMessageId: turn.assistantMessage.id,
+ assistantMessageId: prepared.assistantMessageId,
host,
output: lastOutput,
});
}
- await session.handleError({
- error,
- events,
- interrupted,
- output: lastOutput,
+ await runWithTrace(trace, async () => {
+ await retryPolicy.onError?.({
+ error,
+ events,
+ interrupted,
+ output: lastOutput,
+ });
});
}
throw error;
} finally {
- await session.close(terminalError);
+ await trace?.close(terminalError);
}
};
@@ -157,6 +199,23 @@ const requireContextBuilder = (host: AgentRuntimeHost) => {
return context;
};
+const assertPreparedCallContext = (
+ prepared: Pick<PreparedCallLlmInput, 'context' | 'model' | 'provider' | 'state'>,
+ stepIndex: number,
+) => {
+ if (!prepared.context.resolvedTools) {
+ throw new Error('Resolved tools are required for call_llm');
+ }
+
+ const messages = prepared.context.messages as Array<{ role?: string }>;
+ if (!messages.some((message) => message.role !== 'system')) {
+ throw new Error(
+ `call_llm produced no non-system messages for ${prepared.provider}/${prepared.model} ` +
+ `(topic=${prepared.state.metadata?.topicId ?? 'n/a'}, step=${stepIndex}); refusing to dispatch`,
+ );
+ }
+};
+
const createConversationParentMissingError = (parentId: string) => {
const error = new Error(
`Conversation parent message ${parentId} no longer exists. It was likely deleted while the operation was running.`,
@@ -293,16 +352,22 @@ export const callLlm =
});
try {
- const turn: LLMTurnInput = {
- assistantMessage,
+ const prepared: PreparedCallLlmInput = {
+ assistantMessageId: assistantMessage.id,
context,
model,
provider,
state,
stepLabel,
};
- const session = await llm.openTurn(turn);
- return await executeTurnSession(host, session, turn);
+ assertPreparedCallContext(prepared, operation.stepIndex);
+ const trace = llm.createTrace?.({
+ assistantMessageId: assistantMessage.id,
+ conversationId: state.metadata?.topicId,
+ model,
+ provider,
+ });
+ return await executePreparedCall(host, llm, prepared, trace);
} catch (error) {
await transports.stream.publishError?.({
error,
diff --git a/packages/agent-runtime/src/transport/host.ts b/packages/agent-runtime/src/transport/host.ts
index b0229ccf18c..0eebe1e41a6 100644
--- a/packages/agent-runtime/src/transport/host.ts
+++ b/packages/agent-runtime/src/transport/host.ts
@@ -37,7 +37,7 @@ export interface RuntimeTransports {
}
/**
- * Single argument to the (future) package-hosted executor factories. The server
+ * Single argument to the package-hosted executor factories. The server
* builds this once per operation — wiring its adapters + lifecycle dispatcher +
* operation context — and the package owns the executor logic. This is the seam
* that lets the same executors run on server and client (target end-state of the
diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.ts
index da665be1907..9d6fdf47a8e 100644
--- a/packages/agent-runtime/src/transport/llm.ts
+++ b/packages/agent-runtime/src/transport/llm.ts
@@ -11,7 +11,6 @@ import type {
import type { AgentEvent, AgentState, CallLLMPayload } from '../types';
import type { ClassifiedLLMError } from '../utils';
import type { ContextBuildOutput } from './context';
-import type { RuntimeMessageRef } from './message';
export interface LLMStreamPayload {
[key: string]: unknown;
@@ -23,11 +22,8 @@ export interface LLMStreamPayload {
}
/**
- * Aggregated result of one model turn.
- *
- * NOTE (scaffolding): only the always-present fields are pinned. usage / cost /
- * toolCalls / images / finishReason firm when `call_llm` (Tier C) migrates onto
- * the port — that migration is what actually dissolves the 1700-line executor.
+ * Aggregated result for lightweight stream consumers such as context
+ * compression. Full `call_llm` execution uses {@link LLMAttemptOutput}.
*/
export interface LLMStreamResult {
[key: string]: unknown;
@@ -78,21 +74,7 @@ export interface LLMAttemptInput {
export type LLMAttemptExecution =
{ error: unknown; ok: false; output: LLMAttemptOutput } | { ok: true; output: LLMAttemptOutput };
-export interface LLMTurnInput {
- assistantMessage: RuntimeMessageRef;
- context: ContextBuildOutput;
- model: string;
- provider: string;
- state: AgentState;
- stepLabel?: string;
-}
-
-export interface LLMTurnAttemptInput {
- attempt: number;
- events: AgentEvent[];
-}
-
-export interface LLMTurnErrorInput {
+export interface LLMCallErrorInput {
error: unknown;
events: AgentEvent[];
interrupted: boolean;
@@ -100,24 +82,35 @@ export interface LLMTurnErrorInput {
retryBudget?: number;
}
-export interface LLMTurnRetryInput {
+export interface LLMRetryInput {
attempt: number;
delayMs: number;
error: ClassifiedLLMError;
maxAttempts: number;
}
-/** Host-bound lifecycle for one logical model turn across all retry attempts. */
-export interface LLMTurnSession {
+export interface LLMRetryPolicy {
classifyError: (error: unknown) => ClassifiedLLMError;
+ maxAttempts: (provider: string) => number;
+ onError?: (input: LLMCallErrorInput) => Promise<void> | void;
+ onRetry?: (input: LLMRetryInput) => Promise<void> | void;
+ resolveRetryBudget: (provider: string, error: unknown) => number;
+ waitForRetry?: (delayMs: number) => Promise<void>;
+}
+
+export interface LLMTraceInput {
+ assistantMessageId: string;
+ conversationId?: string;
+ model: string;
+ provider: string;
+}
+
+/** Narrow tracing scope shared by all attempts in one package-owned call. */
+export interface LLMTrace {
close: (error?: unknown) => Promise<void> | void;
- handleError: (input: LLMTurnErrorInput) => Promise<void>;
- maxAttempts: number;
- onRetry?: (input: LLMTurnRetryInput) => Promise<void> | void;
+ onFirstChunk: () => void;
recordResult?: (output: LLMAttemptOutput) => Promise<void> | void;
- resolveRetryBudget: (error: unknown) => number;
- runAttempt: (input: LLMTurnAttemptInput) => Promise<LLMAttemptExecution>;
- waitForRetry?: (delayMs: number) => Promise<void>;
+ run: <T>(task: () => Promise<T>) => Promise<T>;
}
/**
@@ -130,11 +123,10 @@ export interface LLMTurnSession {
* `@lobechat/model-runtime`.
*/
export interface LLMTransport {
- /**
- * Opens a host-bound turn session. The package owns turn orchestration and
- * finalization while the session retains provider policy and tracing hooks.
- */
- openTurn?: (input: LLMTurnInput) => Promise<LLMTurnSession> | LLMTurnSession;
+ /** Creates an optional host tracing scope; no instruction orchestration lives behind it. */
+ createTrace?: (input: LLMTraceInput) => LLMTrace;
+ /** Host extensions for provider retry policy and error diagnostics. */
+ retryPolicy?: LLMRetryPolicy;
/** Executes one model attempt and returns both successful or partial output. */
runAttempt?: (input: LLMAttemptInput) => Promise<LLMAttemptExecution>;
stream: (
diff --git a/packages/agent-runtime/src/transport/stream.ts b/packages/agent-runtime/src/transport/stream.ts
index bc8c704ab7b..92e448fd6b8 100644
--- a/packages/agent-runtime/src/transport/stream.ts
+++ b/packages/agent-runtime/src/transport/stream.ts
@@ -18,9 +18,9 @@ export interface RuntimeStreamEvent {
/**
* Incremental token delta pushed during a step (the other stream channel).
*
- * NOTE (scaffolding): the exact delta union (text / reasoning / tool-call /
- * grounding / image) firms when the first streaming executor (call_llm, Tier C)
- * migrates onto the port.
+ * The exact delta union remains open until client convergence; server and
+ * client adapters may carry text, reasoning, tool-call, grounding, or image
+ * fields while sharing the stable step scope.
*/
export interface StreamChunkInput {
[key: string]: unknown;