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(agent-runtime): host the finish executor in the package behind transport ports (#16549)

Arvin Xu892837b7ba80
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
index 2ca32d310cf..9e427ba03cb 100644
--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
@@ -1,36 +1,40 @@
-import { type AgentInstruction, type InstructionExecutor } from '@lobechat/agent-runtime';
+import {
+ type AgentInstruction,
+ finish as createFinishExecutor,
+ type InstructionExecutor,
+} from '@lobechat/agent-runtime';
+import { buildHost } from './buildHost';
import { type RuntimeExecutorContext } from './context';
import { callLlm } from './executors/callLlm';
import { callTool } from './executors/callTool';
import { callToolsBatch } from './executors/callToolsBatch';
import { compressContext } from './executors/compressContext';
import { execSubAgent, execSubAgents } from './executors/execSubAgent';
-import { finish } from './executors/finish';
import { requestHumanApprove } from './executors/humanApprove';
import { resolveAbortedTools, resolveBlockedTools } from './executors/resolveTools';
export { type RuntimeExecutorContext } from './context';
-/**
- * Assemble the per-instruction executors for one agent-runtime operation.
- *
- * Each executor is a self-contained module under `./executors/*`; this factory
- * only wires them to the shared {@link RuntimeExecutorContext}. The executors
- * close over nothing but `ctx`, so the wiring here is pure composition β€” see the
- * individual files for the actual logic.
- */
export const createRuntimeExecutors = (
ctx: RuntimeExecutorContext,
-): Partial<Record<AgentInstruction['type'], InstructionExecutor>> => ({
- call_llm: callLlm(ctx),
- call_tool: callTool(ctx),
- call_tools_batch: callToolsBatch(ctx),
- compress_context: compressContext(ctx),
- exec_sub_agent: execSubAgent(ctx),
- exec_sub_agents: execSubAgents(ctx),
- finish: finish(ctx),
- request_human_approve: requestHumanApprove(ctx),
- resolve_aborted_tools: resolveAbortedTools(ctx),
- resolve_blocked_tools: resolveBlockedTools(ctx),
-});
+): Partial<Record<AgentInstruction['type'], InstructionExecutor>> => {
+ // Package-hosted executors take an AgentRuntimeHost (transport adapters +
+ // operation context) instead of the raw server ctx. Built once per operation.
+ const host = buildHost(ctx);
+
+ return {
+ call_llm: callLlm(ctx),
+ call_tool: callTool(ctx),
+ call_tools_batch: callToolsBatch(ctx),
+ compress_context: compressContext(ctx),
+ exec_sub_agent: execSubAgent(ctx),
+ exec_sub_agents: execSubAgents(ctx),
+ // Migrated into @lobechat/agent-runtime (LOBE-10949 Tier A) β€” server only
+ // registers the adapters via buildHost.
+ finish: createFinishExecutor(host),
+ request_human_approve: requestHumanApprove(ctx),
+ resolve_aborted_tools: resolveAbortedTools(ctx),
+ resolve_blocked_tools: resolveBlockedTools(ctx),
+ };
+};
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
new file mode 100644
index 00000000000..1e9b2730958
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
@@ -0,0 +1,54 @@
+import type {
+ MessageTransport,
+ QueryMessagesInput,
+ RuntimeMessageRef,
+ UpdateToolMessageInput,
+} from '@lobechat/agent-runtime';
+import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@lobechat/types';
+
+import { type MessageModel } from '@/database/models/message';
+
+/**
+ * Server {@link MessageTransport} adapter β€” delegates to `MessageModel` (DB).
+ *
+ * NOTE: DB-error normalization (PG FK-violation β†’ typed user-side error) is a
+ * DB-backed-transport concern and will be folded in here when the persisting
+ * executors (`resolve_*`, `call_tool`) migrate; today's callers keep their own
+ * catch blocks, so this stays a thin delegation.
+ */
+export class ServerMessageTransport implements MessageTransport {
+ constructor(private readonly messageModel: MessageModel) {}
+
+ createAssistantMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {
+ return this.messageModel.create(params);
+ }
+
+ createToolMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {
+ return this.messageModel.create(params);
+ }
+
+ async deleteMessage(id: string): Promise<void> {
+ await this.messageModel.deleteMessage(id);
+ }
+
+ async findById(id: string): Promise<RuntimeMessageRef | undefined> {
+ const message = await this.messageModel.findById(id);
+ return message ? { id: message.id } : undefined;
+ }
+
+ query(params?: QueryMessagesInput): Promise<UIChatMessage[]> {
+ return this.messageModel.query(params);
+ }
+
+ async update(id: string, params: Partial<UpdateMessageParams>): Promise<void> {
+ await this.messageModel.update(id, params);
+ }
+
+ async updatePluginState(id: string, state: Record<string, any>): Promise<void> {
+ await this.messageModel.updatePluginState(id, state);
+ }
+
+ async updateToolMessage(id: string, params: UpdateToolMessageInput): Promise<void> {
+ await this.messageModel.updateToolMessage(id, params);
+ }
+}
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
new file mode 100644
index 00000000000..dcc3f449e19
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
@@ -0,0 +1,29 @@
+import type { OperationStore } from '@lobechat/agent-runtime';
+
+import { TopicModel } from '@/database/models/topic';
+import { type LobeChatDatabase } from '@/database/type';
+
+/**
+ * Server {@link OperationStore} adapter. `clearRunningMark` drops the topic's
+ * `runningOperation` so a reconnect doesn't re-trigger after completion.
+ * Best-effort: missing topic/user is a no-op and failures are swallowed
+ * (matches the prior server-local `finish` behavior).
+ */
+export class ServerOperationStore implements OperationStore {
+ constructor(
+ private readonly serverDB: LobeChatDatabase,
+ private readonly userId: string | undefined,
+ private readonly workspaceId: string | undefined,
+ private readonly topicId: string | undefined,
+ ) {}
+
+ async clearRunningMark(): Promise<void> {
+ if (!this.topicId || !this.userId) return;
+ try {
+ const topicModel = new TopicModel(this.serverDB, this.userId, this.workspaceId);
+ await topicModel.updateMetadata(this.topicId, { runningOperation: null });
+ } catch {
+ // best-effort β€” swallow
+ }
+ }
+}
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts
new file mode 100644
index 00000000000..e753660a1bd
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts
@@ -0,0 +1,27 @@
+import type { RuntimeStreamEvent, StreamChunkInput, StreamSink } from '@lobechat/agent-runtime';
+
+import { type IStreamEventManager } from '../types';
+
+/**
+ * Server {@link StreamSink} adapter β€” forwards runtime stream events/chunks to
+ * the operation's Redis stream. Binds `operationId` so the package executor
+ * stays unaware of it.
+ */
+export class ServerStreamSink implements StreamSink {
+ constructor(
+ private readonly streamManager: IStreamEventManager,
+ private readonly operationId: string,
+ ) {}
+
+ async publishChunk(chunk: StreamChunkInput): Promise<void> {
+ await this.streamManager.publishStreamChunk(this.operationId, chunk.stepIndex, chunk as any);
+ }
+
+ async publishEvent(event: RuntimeStreamEvent): Promise<void> {
+ await this.streamManager.publishStreamEvent(this.operationId, {
+ data: event.data,
+ stepIndex: event.stepIndex,
+ type: event.type,
+ } as any);
+ }
+}
diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.ts
new file mode 100644
index 00000000000..138842eed81
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts
@@ -0,0 +1,36 @@
+import type { AgentRuntimeHost } from '@lobechat/agent-runtime';
+
+import { ServerMessageTransport } from './adapters/ServerMessageTransport';
+import { ServerOperationStore } from './adapters/ServerOperationStore';
+import { ServerStreamSink } from './adapters/ServerStreamSink';
+import { type RuntimeExecutorContext } from './context';
+
+/**
+ * Build the {@link AgentRuntimeHost} from the server's `RuntimeExecutorContext`:
+ * wraps the concrete services (`MessageModel`, `IStreamEventManager`,
+ * `TopicModel`) in transport adapters + assembles the operation context. This
+ * is the "server only registers adapters" seam β€” package-hosted executors take
+ * the host instead of the raw ctx.
+ *
+ * Grows as more executors migrate (tools / llm / context / blob / lifecycle
+ * adapters get added here); today it covers the `finish` executor.
+ */
+export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => ({
+ operation: {
+ operationId: ctx.operationId,
+ stepIndex: ctx.stepIndex,
+ topicId: ctx.topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ },
+ transports: {
+ messages: new ServerMessageTransport(ctx.messageModel),
+ operationStore: new ServerOperationStore(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ctx.topicId,
+ ),
+ stream: new ServerStreamSink(ctx.streamManager, ctx.operationId),
+ },
+});
diff --git a/apps/server/src/modules/AgentRuntime/executors/finish.ts b/apps/server/src/modules/AgentRuntime/executors/finish.ts
deleted file mode 100644
index a17f52f1ddb..00000000000
--- a/apps/server/src/modules/AgentRuntime/executors/finish.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import {
- type AgentEvent,
- type AgentInstruction,
- type InstructionExecutor,
-} from '@lobechat/agent-runtime';
-
-import { TopicModel } from '@/database/models/topic';
-
-import { type RuntimeExecutorContext } from '../context';
-import { log } from '../executorHelpers';
-
-export const finish =
- (ctx: RuntimeExecutorContext): InstructionExecutor =>
- async (instruction, state) => {
- const { reason, reasonDetail } = instruction as Extract<AgentInstruction, { type: 'finish' }>;
- const { operationId, stepIndex, streamManager } = ctx;
-
- log('[%s:%d] Finishing execution: (%s)', operationId, stepIndex, reason);
-
- // Clear runningOperation from topic metadata so reconnect doesn't trigger after completion
- if (ctx.topicId && ctx.userId) {
- try {
- const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
- await topicModel.updateMetadata(ctx.topicId, { runningOperation: null });
- } catch (e) {
- log('[%s] Failed to clear runningOperation metadata: %O', operationId, e);
- }
- }
-
- // Publish execution complete event. `finalState.messages` + tool-set
- // fields are stripped centrally inside `publishStreamEvent` so this
- // call site stays unaware.
- await streamManager.publishStreamEvent(operationId, {
- data: {
- finalState: { ...state, status: 'done' },
- phase: 'execution_complete',
- reason,
- reasonDetail,
- },
- stepIndex,
- type: 'step_complete',
- });
-
- const newState = structuredClone(state);
- newState.lastModified = new Date().toISOString();
- newState.status = 'done';
-
- const events: AgentEvent[] = [
- {
- finalState: newState,
- reason,
- reasonDetail,
- type: 'done',
- },
- ];
-
- return { events, newState };
- };
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 7a00fb7691c..275eb0eff12 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -102,18 +102,14 @@ vi.mock('@/server/modules/AgentRuntime', async (importOriginal) => {
};
});
-vi.mock('@lobechat/agent-runtime', () => ({
+// Spread the real module and override only `AgentRuntime` (to stub `.step()`).
+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),
+// so this mock survives future executor migrations without edits.
+vi.mock('@lobechat/agent-runtime', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
AgentRuntime: vi.fn().mockImplementation((_agent, _options) => ({
step: vi.fn(),
})),
- // Mirror the real status predicates (packages/agent-runtime/src/utils/status.ts)
- // so completion-lifecycle / getOperationStatus paths don't crash on the mock.
- isBlockedStatus: (status: string) =>
- status === 'waiting_for_human' ||
- status === 'waiting_for_async_tool' ||
- status === 'interrupted',
- isParkedStatus: (status: string) =>
- status === 'waiting_for_human' || status === 'waiting_for_async_tool',
}));
vi.mock('@/server/services/queue', () => ({
diff --git a/packages/agent-runtime/src/executors/finish.ts b/packages/agent-runtime/src/executors/finish.ts
new file mode 100644
index 00000000000..38455d06eef
--- /dev/null
+++ b/packages/agent-runtime/src/executors/finish.ts
@@ -0,0 +1,43 @@
+import type { AgentRuntimeHost } from '../transport';
+import type { AgentEvent, AgentInstruction, InstructionExecutor } from '../types';
+
+/**
+ * `finish` executor β€” terminates the operation.
+ *
+ * First executor hosted in the package (LOBE-10949 Tier A): it depends only on
+ * the `StreamSink` + `OperationStore` transports and the operation context, so
+ * the server just provides those adapters. Behavior mirrors the previous
+ * server-local implementation exactly.
+ */
+export const finish =
+ (host: AgentRuntimeHost): InstructionExecutor =>
+ async (instruction, state) => {
+ const { reason, reasonDetail } = instruction as Extract<AgentInstruction, { type: 'finish' }>;
+ const { operation, transports } = host;
+
+ // Clear the topic's running-operation mark so a reconnect doesn't
+ // re-trigger after completion. Best-effort β€” the adapter swallows failures.
+ await transports.operationStore?.clearRunningMark();
+
+ // Publish the execution-complete stream event. `finalState.messages` +
+ // tool-set fields are stripped centrally inside the sink adapter, so this
+ // call site stays unaware.
+ await transports.stream.publishEvent({
+ data: {
+ finalState: { ...state, status: 'done' },
+ phase: 'execution_complete',
+ reason,
+ reasonDetail,
+ },
+ stepIndex: operation.stepIndex,
+ type: 'step_complete',
+ });
+
+ const newState = structuredClone(state);
+ newState.lastModified = new Date().toISOString();
+ newState.status = 'done';
+
+ const events: AgentEvent[] = [{ finalState: newState, reason, reasonDetail, type: 'done' }];
+
+ return { events, newState };
+ };
diff --git a/packages/agent-runtime/src/executors/index.ts b/packages/agent-runtime/src/executors/index.ts
new file mode 100644
index 00000000000..a9a18bc7275
--- /dev/null
+++ b/packages/agent-runtime/src/executors/index.ts
@@ -0,0 +1 @@
+export * from './finish';
diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.ts
index 84851c57b11..11a8b968866 100644
--- a/packages/agent-runtime/src/index.ts
+++ b/packages/agent-runtime/src/index.ts
@@ -1,6 +1,7 @@
export * from './agents';
export * from './audit';
export * from './core';
+export * from './executors';
export * from './groupOrchestration';
export * from './transport';
export * from './types';
diff --git a/packages/agent-runtime/src/transport/host.ts b/packages/agent-runtime/src/transport/host.ts
index 36fe4f8bda1..fa04c1e158c 100644
--- a/packages/agent-runtime/src/transport/host.ts
+++ b/packages/agent-runtime/src/transport/host.ts
@@ -3,6 +3,7 @@ import type { ContextBuilder } from './context';
import type { LifecycleSink } from './lifecycle';
import type { LLMTransport } from './llm';
import type { MessageTransport } from './message';
+import type { OperationStore, RuntimeOperationContext } from './operation';
import type { StreamSink } from './stream';
import type { SubAgentTransport } from './subAgent';
import type { ToolTransport } from './tool';
@@ -14,17 +15,19 @@ import type { ToolTransport } from './tool';
* are optional because only some executors need them β€” an executor that needs a
* transport asserts its presence at use site:
*
- * - `tools` β†’ call_tool, call_tools_batch
- * - `subAgent` β†’ exec_sub_agent, exec_sub_agents
- * - `llm` β†’ call_llm, compress_context
- * - `context` β†’ call_llm, compress_context
- * - `blob` β†’ call_llm
+ * - `tools` β†’ call_tool, call_tools_batch
+ * - `subAgent` β†’ exec_sub_agent, exec_sub_agents
+ * - `llm` β†’ call_llm, compress_context
+ * - `context` β†’ call_llm, compress_context
+ * - `blob` β†’ call_llm
+ * - `operationStore` β†’ finish, call_llm (interruption guard)
*/
export interface RuntimeTransports {
blob?: BlobStore;
context?: ContextBuilder;
llm?: LLMTransport;
messages: MessageTransport;
+ operationStore?: OperationStore;
stream: StreamSink;
subAgent?: SubAgentTransport;
tools?: ToolTransport;
@@ -32,11 +35,12 @@ export interface RuntimeTransports {
/**
* Single argument to the (future) package-hosted executor factories. The server
- * builds this once per operation β€” wiring its adapters + lifecycle dispatcher β€”
- * and the package owns the executor logic. This is the seam that lets the same
- * executors run on server and client (LOBE-10949 end-state).
+ * 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 (LOBE-10949 end-state).
*/
export interface AgentRuntimeHost {
lifecycle?: LifecycleSink;
+ operation: RuntimeOperationContext;
transports: RuntimeTransports;
}
diff --git a/packages/agent-runtime/src/transport/index.ts b/packages/agent-runtime/src/transport/index.ts
index 44d21566178..fed38aa50c9 100644
--- a/packages/agent-runtime/src/transport/index.ts
+++ b/packages/agent-runtime/src/transport/index.ts
@@ -4,6 +4,7 @@ export * from './host';
export * from './lifecycle';
export * from './llm';
export * from './message';
+export * from './operation';
export * from './stream';
export * from './subAgent';
export * from './tool';
diff --git a/packages/agent-runtime/src/transport/operation.ts b/packages/agent-runtime/src/transport/operation.ts
new file mode 100644
index 00000000000..39fce071630
--- /dev/null
+++ b/packages/agent-runtime/src/transport/operation.ts
@@ -0,0 +1,28 @@
+import type { AgentState } from '../types';
+
+/**
+ * Operation-scoped metadata every executor needs (ids for logging / event
+ * scoping). Distinct from the transports β€” this is per-operation context, not
+ * an injectable capability. The server builds it once per operation from the
+ * request; `stepIndex` advances per step.
+ */
+export interface RuntimeOperationContext {
+ operationId: string;
+ stepIndex: number;
+ topicId?: string;
+ userId?: string;
+ workspaceId?: string;
+}
+
+/**
+ * Operation-lifecycle bookkeeping port. Server adapter wraps the topic /
+ * operation-state models; the client adapter can be a no-op.
+ *
+ * Starts minimal β€” only `clearRunningMark` (used by `finish` to drop the
+ * topic's `runningOperation` so a reconnect doesn't re-trigger). `loadState`
+ * (interruption guard) joins here when call_tool / call_llm migrate.
+ */
+export interface OperationStore {
+ clearRunningMark: () => Promise<void>;
+ loadState?: (operationId: string) => Promise<AgentState | null>;
+}
diff --git a/packages/agent-runtime/src/transport/stream.ts b/packages/agent-runtime/src/transport/stream.ts
index b675a878511..70d04fbba37 100644
--- a/packages/agent-runtime/src/transport/stream.ts
+++ b/packages/agent-runtime/src/transport/stream.ts
@@ -1,12 +1,26 @@
-import type { AgentEvent } from '../types';
+/**
+ * A live transport-layer stream event (distinct from the engine's `AgentEvent`
+ * returned in the step result). Mirrors the server `IStreamEventManager`
+ * protocol: a `type` discriminator (`step_start` | `step_complete` | `tool_end`
+ * | `error` | …) plus a type-specific `data` payload, scoped to a step.
+ *
+ * NOTE: `type` is left as `string` for now β€” the full server taxonomy is not
+ * yet modeled in the package. It firms (and gains a union) when the client
+ * converges onto the same protocol (P6). `operationId` is bound by the adapter,
+ * not carried here.
+ */
+export interface RuntimeStreamEvent {
+ data: unknown;
+ stepIndex: number;
+ type: string;
+}
/**
- * Incremental streaming delta pushed to the consumer during a step.
+ * Incremental token delta pushed during a step (the other stream channel).
*
* NOTE (scaffolding): the exact delta union (text / reasoning / tool-call /
- * grounding / image) is server-defined today (`StreamChunkData`). It is
- * intentionally left open here and will be firmed when the first streaming
- * executor (call_llm, Tier C) migrates onto the port.
+ * grounding / image) firms when the first streaming executor (call_llm, Tier C)
+ * migrates onto the port.
*/
export interface StreamChunkInput {
[key: string]: unknown;
@@ -18,12 +32,8 @@ export interface StreamChunkInput {
/**
* Egress for live streaming. Server adapter forwards to the Redis stream
* (`IStreamEventManager`); the client adapter dispatches into the UI store.
- *
- * The runtime emits its native {@link AgentEvent}s β€” the adapter is responsible
- * for translating them to the wire/UI shape, so the package never depends on a
- * transport-specific event format.
*/
export interface StreamSink {
- publishChunk: (chunk: StreamChunkInput) => Promise<void> | void;
- publishEvent: (event: AgentEvent) => Promise<void> | void;
+ publishChunk: (chunk: StreamChunkInput) => Promise<void>;
+ publishEvent: (event: RuntimeStreamEvent) => Promise<void>;
}