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.

✨ feat(agent-runtime): host the request_human_approve executor in the package (#16581)

Arvin Xu761826041770
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
index 8240eba176f..150e6511cd5 100644
--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
@@ -2,6 +2,7 @@ import {
type AgentInstruction,
finish as createFinishExecutor,
type InstructionExecutor,
+ requestHumanApprove as createRequestHumanApproveExecutor,
} from '@lobechat/agent-runtime';
import { buildHost } from './buildHost';
@@ -11,7 +12,6 @@ import { callTool } from './executors/callTool';
import { callToolsBatch } from './executors/callToolsBatch';
import { compressContext } from './executors/compressContext';
import { execSubAgent, execSubAgents } from './executors/execSubAgent';
-import { requestHumanApprove } from './executors/humanApprove';
import { resolveAbortedTools, resolveBlockedTools } from './executors/resolveTools';
export { type RuntimeExecutorContext } from './context';
@@ -33,7 +33,7 @@ export const createRuntimeExecutors = (
// Migrated into @lobechat/agent-runtime as part of the IO transport port
// abstraction β€” the server now only registers adapters via buildHost.
finish: createFinishExecutor(host),
- request_human_approve: requestHumanApprove(ctx),
+ request_human_approve: createRequestHumanApproveExecutor(host),
resolve_aborted_tools: resolveAbortedTools(ctx),
resolve_blocked_tools: resolveBlockedTools(ctx),
};
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLifecycleSink.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLifecycleSink.ts
new file mode 100644
index 00000000000..6735d7a4fbc
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLifecycleSink.ts
@@ -0,0 +1,38 @@
+import type {
+ LifecycleDispatchParams,
+ LifecycleSink,
+ ToolCallMockResult,
+} from '@lobechat/agent-runtime';
+
+import { type HookDispatcher } from '@/server/services/agentRuntime/hooks/HookDispatcher';
+
+/**
+ * Server {@link LifecycleSink} adapter β€” forwards runtime lifecycle dispatches
+ * to the operation's `HookDispatcher`, binding `operationId`. `serializedHooks`
+ * (the per-operation webhook configs the executor reads off `state.metadata`)
+ * is passed through for production/queue mode.
+ */
+export class ServerLifecycleSink implements LifecycleSink {
+ constructor(
+ private readonly hookDispatcher: HookDispatcher,
+ private readonly operationId: string,
+ ) {}
+
+ async dispatch({ type, event, serializedHooks }: LifecycleDispatchParams): Promise<void> {
+ await this.hookDispatcher.dispatch(
+ this.operationId,
+ type as any,
+ event as any,
+ serializedHooks as any,
+ );
+ }
+
+ async dispatchBeforeToolCall(
+ event: Parameters<LifecycleSink['dispatchBeforeToolCall']>[0],
+ ): Promise<ToolCallMockResult | null> {
+ return (await this.hookDispatcher.dispatchBeforeToolCall(
+ this.operationId,
+ event as any,
+ )) as ToolCallMockResult | null;
+ }
+}
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts
index e753660a1bd..42513a91252 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts
@@ -14,7 +14,9 @@ export class ServerStreamSink implements StreamSink {
) {}
async publishChunk(chunk: StreamChunkInput): Promise<void> {
- await this.streamManager.publishStreamChunk(this.operationId, chunk.stepIndex, chunk as any);
+ // `stepIndex` is a positional arg to the manager, not part of the chunk data.
+ const { stepIndex, ...data } = chunk;
+ await this.streamManager.publishStreamChunk(this.operationId, stepIndex, data as any);
}
async publishEvent(event: RuntimeStreamEvent): Promise<void> {
diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.ts
index 138842eed81..9bed32b5cd8 100644
--- a/apps/server/src/modules/AgentRuntime/buildHost.ts
+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts
@@ -1,5 +1,6 @@
import type { AgentRuntimeHost } from '@lobechat/agent-runtime';
+import { ServerLifecycleSink } from './adapters/ServerLifecycleSink';
import { ServerMessageTransport } from './adapters/ServerMessageTransport';
import { ServerOperationStore } from './adapters/ServerOperationStore';
import { ServerStreamSink } from './adapters/ServerStreamSink';
@@ -16,6 +17,11 @@ import { type RuntimeExecutorContext } from './context';
* adapters get added here); today it covers the `finish` executor.
*/
export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => ({
+ // Only present when the operation registered hooks β€” mirrors the prior
+ // `if (ctx.hookDispatcher)` guard in the human-approve executor.
+ lifecycle: ctx.hookDispatcher
+ ? new ServerLifecycleSink(ctx.hookDispatcher, ctx.operationId)
+ : undefined,
operation: {
operationId: ctx.operationId,
stepIndex: ctx.stepIndex,
diff --git a/apps/server/src/modules/AgentRuntime/executors/humanApprove.ts b/apps/server/src/modules/AgentRuntime/executors/humanApprove.ts
deleted file mode 100644
index 44815a57ac5..00000000000
--- a/apps/server/src/modules/AgentRuntime/executors/humanApprove.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import {
- type AgentEvent,
- type AgentInstruction,
- type InstructionExecutor,
-} from '@lobechat/agent-runtime';
-
-import { type RuntimeExecutorContext } from '../context';
-import { log } from '../executorHelpers';
-
-export const requestHumanApprove =
- (ctx: RuntimeExecutorContext): InstructionExecutor =>
- async (instruction, state) => {
- const { pendingToolsCalling, skipCreateToolMessage } = instruction as Extract<
- AgentInstruction,
- { type: 'request_human_approve' }
- >;
- const { operationId, stepIndex, streamManager } = ctx;
-
- log('[%s:%d] Requesting human approval for %O', operationId, stepIndex, pendingToolsCalling);
-
- // Publish human approval request event
- await streamManager.publishStreamEvent(operationId, {
- data: {
- pendingToolsCalling,
- phase: 'human_approval',
- requiresApproval: true,
- },
- stepIndex,
- type: 'step_start',
- });
-
- if (ctx.hookDispatcher) {
- ctx.hookDispatcher
- .dispatch(
- operationId,
- 'beforeHumanIntervention',
- {
- operationId,
- pendingTools: pendingToolsCalling.map((t: any) => ({
- apiName: t.apiName,
- identifier: t.identifier,
- })),
- stepIndex,
- userId: ctx.userId,
- },
- state.metadata?._hooks,
- )
- .catch(() => {});
- }
-
- const newState = structuredClone(state);
- newState.lastModified = new Date().toISOString();
- newState.status = 'waiting_for_human';
- newState.pendingToolsCalling = pendingToolsCalling;
-
- // Map of toolCallId -> toolMessageId, populated either by creating fresh
- // pending tool messages or (in resumption mode) by looking up existing ones.
- const toolMessageIds: Record<string, string> = {};
-
- if (skipCreateToolMessage) {
- // Resumption mode: tool messages already exist in DB. Look them up by
- // tool_call_id so we can still ship the mapping to the client.
- log('[%s:%d] Resuming with existing tool messages', operationId, stepIndex);
- try {
- const dbMessages = await ctx.messageModel.query({
- agentId: state.metadata?.agentId,
- // Group runs need groupId or the query returns no group messages, so
- // the existing tool-message lookup on resume would find nothing.
- groupId: state.metadata?.groupId,
- threadId: state.metadata?.threadId,
- topicId: state.metadata?.topicId,
- });
- for (const toolPayload of pendingToolsCalling) {
- const existing = dbMessages.find(
- (m: any) => m.role === 'tool' && m.tool_call_id === toolPayload.id,
- );
- if (existing) {
- toolMessageIds[toolPayload.id] = existing.id;
- }
- }
- } catch (error) {
- console.error(
- '[%s:%d] Failed to look up existing tool messages: %O',
- operationId,
- stepIndex,
- error,
- );
- }
- } else {
- // Find parent assistant message. Prefer state.messages (already in
- // memory from call_llm); fall back to DB query if the runtime has been
- // rehydrated without recent messages.
- let parentAssistantId: string | undefined = (state.messages ?? [])
- .slice()
- .reverse()
- .find((m: any) => m.role === 'assistant' && m.id)?.id;
-
- if (!parentAssistantId) {
- try {
- const dbMessages = await ctx.messageModel.query({
- agentId: state.metadata?.agentId,
- // Group runs need groupId or the query returns no group messages, so
- // the parent-assistant fallback lookup would find nothing.
- groupId: state.metadata?.groupId,
- threadId: state.metadata?.threadId,
- topicId: state.metadata?.topicId,
- });
- parentAssistantId = dbMessages
- .slice()
- .reverse()
- .find((m: any) => m.role === 'assistant')?.id;
- } catch (error) {
- console.error(
- '[%s:%d] Failed to query DB for parent assistant: %O',
- operationId,
- stepIndex,
- error,
- );
- }
- }
-
- if (!parentAssistantId) {
- throw new Error(
- `[request_human_approve] No assistant message found as parent for pending tool messages (op=${operationId})`,
- );
- }
-
- for (const toolPayload of pendingToolsCalling) {
- const toolName = `${toolPayload.identifier}/${toolPayload.apiName}`;
- try {
- const toolMessage = await ctx.messageModel.create({
- agentId: state.metadata!.agentId!,
- content: '',
- groupId: state.metadata?.groupId ?? undefined,
- parentId: parentAssistantId,
- plugin: toolPayload as any,
- pluginIntervention: { status: 'pending' },
- role: 'tool',
- threadId: state.metadata?.threadId,
- tool_call_id: toolPayload.id,
- topicId: state.metadata?.topicId,
- });
-
- toolMessageIds[toolPayload.id] = toolMessage.id;
-
- // Intentionally DO NOT push the empty placeholder into
- // newState.messages. When the approval resumes, the `call_tool`
- // executor (skip-create branch) appends the resolved tool message
- // to state.messages itself. Pushing a placeholder here produced
- // two entries for the same tool_call_id β€” see review P2.
-
- log(
- '[%s:%d] Created pending tool message %s for %s',
- operationId,
- stepIndex,
- toolMessage.id,
- toolName,
- );
- } catch (error) {
- console.error(
- '[%s:%d] Failed to create pending tool message for %s: %O',
- operationId,
- stepIndex,
- toolName,
- error,
- );
- throw error;
- }
- }
- }
-
- // Notify frontend to display approval UI through streaming system.
- // `toolMessageIds` is a new optional field; legacy consumers ignore it.
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'tools_calling',
- toolMessageIds,
- toolsCalling: pendingToolsCalling as any,
- } as any);
-
- const events: AgentEvent[] = [
- {
- operationId,
- pendingToolsCalling,
- type: 'human_approve_required',
- },
- {
- // Note: pendingToolsCalling is ChatToolPayload[] but AgentEventToolPending expects ToolsCalling[]
- // This is intentional for display purposes in the frontend
- toolCalls: pendingToolsCalling as any,
- type: 'tool_pending',
- },
- ];
-
- log('Human approval requested for operation %s:%d', operationId, stepIndex);
-
- return {
- events,
- newState,
- // Do not provide nextContext as it requires waiting for human intervention
- };
- };
diff --git a/packages/agent-runtime/src/executors/humanApprove.ts b/packages/agent-runtime/src/executors/humanApprove.ts
new file mode 100644
index 00000000000..2baa80c8a81
--- /dev/null
+++ b/packages/agent-runtime/src/executors/humanApprove.ts
@@ -0,0 +1,169 @@
+import type { AgentRuntimeHost } from '../transport';
+import type { AgentEvent, AgentInstruction, AnyHookEvent, InstructionExecutor } from '../types';
+
+/**
+ * `request_human_approve` executor β€” pauses the operation for human tool
+ * approval (LOBE-10949 Tier A).
+ *
+ * Uses the `StreamSink` (event + chunk channels), `LifecycleSink`
+ * (`beforeHumanIntervention` hook) and `MessageTransport` (create pending tool
+ * messages / look them up on resume). Behavior mirrors the previous
+ * server-local implementation.
+ */
+export const requestHumanApprove =
+ (host: AgentRuntimeHost): InstructionExecutor =>
+ async (instruction, state) => {
+ const { pendingToolsCalling, skipCreateToolMessage } = instruction as Extract<
+ AgentInstruction,
+ { type: 'request_human_approve' }
+ >;
+ const { operation, transports, lifecycle } = host;
+ const { operationId, stepIndex, userId } = operation;
+
+ // Publish human approval request event
+ await transports.stream.publishEvent({
+ data: {
+ pendingToolsCalling,
+ phase: 'human_approval',
+ requiresApproval: true,
+ },
+ stepIndex,
+ type: 'step_start',
+ });
+
+ // Fire-and-forget lifecycle hook (webhook configs carried via state).
+ lifecycle
+ ?.dispatch({
+ event: {
+ operationId,
+ pendingTools: pendingToolsCalling.map((t: any) => ({
+ apiName: t.apiName,
+ identifier: t.identifier,
+ })),
+ stepIndex,
+ userId,
+ } as AnyHookEvent,
+ serializedHooks: state.metadata?._hooks,
+ type: 'beforeHumanIntervention',
+ })
+ .catch(() => {});
+
+ const newState = structuredClone(state);
+ newState.lastModified = new Date().toISOString();
+ newState.status = 'waiting_for_human';
+ newState.pendingToolsCalling = pendingToolsCalling;
+
+ // Map of toolCallId -> toolMessageId, populated either by creating fresh
+ // pending tool messages or (in resumption mode) by looking up existing ones.
+ const toolMessageIds: Record<string, string> = {};
+
+ if (skipCreateToolMessage) {
+ // Resumption mode: tool messages already exist. Look them up by
+ // tool_call_id so we can still ship the mapping to the client.
+ try {
+ const dbMessages = await transports.messages.query({
+ agentId: state.metadata?.agentId,
+ // Group runs need groupId or the query returns no group messages, so
+ // the existing tool-message lookup on resume would find nothing.
+ groupId: state.metadata?.groupId,
+ threadId: state.metadata?.threadId,
+ topicId: state.metadata?.topicId,
+ });
+ for (const toolPayload of pendingToolsCalling) {
+ const existing = dbMessages.find(
+ (m: any) => m.role === 'tool' && m.tool_call_id === toolPayload.id,
+ );
+ if (existing) {
+ toolMessageIds[toolPayload.id] = existing.id;
+ }
+ }
+ } catch {
+ // best-effort lookup β€” a miss just omits the mapping
+ }
+ } else {
+ // Find parent assistant message. Prefer state.messages (already in
+ // memory from call_llm); fall back to a query if the runtime has been
+ // rehydrated without recent messages.
+ let parentAssistantId: string | undefined = (state.messages ?? [])
+ .slice()
+ .reverse()
+ .find((m: any) => m.role === 'assistant' && m.id)?.id;
+
+ if (!parentAssistantId) {
+ try {
+ const dbMessages = await transports.messages.query({
+ agentId: state.metadata?.agentId,
+ // Group runs need groupId or the query returns no group messages, so
+ // the parent-assistant fallback lookup would find nothing.
+ groupId: state.metadata?.groupId,
+ threadId: state.metadata?.threadId,
+ topicId: state.metadata?.topicId,
+ });
+ parentAssistantId = dbMessages
+ .slice()
+ .reverse()
+ .find((m: any) => m.role === 'assistant')?.id;
+ } catch {
+ // fall through to the missing-parent guard below
+ }
+ }
+
+ if (!parentAssistantId) {
+ throw new Error(
+ `[request_human_approve] No assistant message found as parent for pending tool messages (op=${operationId})`,
+ );
+ }
+
+ for (const toolPayload of pendingToolsCalling) {
+ const toolMessage = await transports.messages.createToolMessage({
+ agentId: state.metadata!.agentId!,
+ content: '',
+ groupId: state.metadata?.groupId ?? undefined,
+ parentId: parentAssistantId,
+ plugin: toolPayload as any,
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ threadId: state.metadata?.threadId,
+ tool_call_id: toolPayload.id,
+ topicId: state.metadata?.topicId,
+ });
+
+ toolMessageIds[toolPayload.id] = toolMessage.id;
+
+ // Intentionally DO NOT push the empty placeholder into
+ // newState.messages. When the approval resumes, the `call_tool`
+ // executor (skip-create branch) appends the resolved tool message to
+ // state.messages itself. Pushing a placeholder here produced two
+ // entries for the same tool_call_id.
+ }
+ }
+
+ // Notify frontend to display approval UI through streaming system.
+ // `toolMessageIds` is a new optional field; legacy consumers ignore it.
+ await transports.stream.publishChunk({
+ chunkType: 'tools_calling',
+ stepIndex,
+ toolMessageIds,
+ toolsCalling: pendingToolsCalling as any,
+ });
+
+ const events: AgentEvent[] = [
+ {
+ operationId,
+ pendingToolsCalling,
+ type: 'human_approve_required',
+ },
+ {
+ // pendingToolsCalling is ChatToolPayload[] but AgentEventToolPending
+ // expects ToolsCalling[]; intentional for frontend display.
+ toolCalls: pendingToolsCalling as any,
+ type: 'tool_pending',
+ },
+ ];
+
+ return {
+ events,
+ newState,
+ // No nextContext β€” the operation waits for human intervention.
+ };
+ };
diff --git a/packages/agent-runtime/src/executors/index.ts b/packages/agent-runtime/src/executors/index.ts
index a9a18bc7275..9ec04f6b4d5 100644
--- a/packages/agent-runtime/src/executors/index.ts
+++ b/packages/agent-runtime/src/executors/index.ts
@@ -1 +1,2 @@
export * from './finish';
+export * from './humanApprove';
diff --git a/packages/agent-runtime/src/transport/lifecycle.ts b/packages/agent-runtime/src/transport/lifecycle.ts
index 14cd751d08f..35c29c5af00 100644
--- a/packages/agent-runtime/src/transport/lifecycle.ts
+++ b/packages/agent-runtime/src/transport/lifecycle.ts
@@ -5,6 +5,19 @@ export interface ToolCallMockResult {
isMocked: true;
}
+export interface LifecycleDispatchParams {
+ /** The lifecycle hook event payload. */
+ event: AnyHookEvent;
+ /**
+ * Per-operation webhook configs (the server keeps them on
+ * `state.metadata._hooks` for production/queue mode). Opaque to the package
+ * and forwarded verbatim to the adapter.
+ */
+ serializedHooks?: unknown;
+ /** Which of the coarse-grained hook types this dispatch fires. */
+ type: AgentHookType;
+}
+
/**
* Lifecycle dispatch port. Decouples executors from the server-side
* `HookDispatcher`: an executor calls `lifecycle.dispatch(...)` at its key
@@ -19,7 +32,7 @@ export interface ToolCallMockResult {
* to skip real execution); everything else is fire-and-forget observation.
*/
export interface LifecycleSink {
- dispatch: (type: AgentHookType, event: AnyHookEvent) => Promise<void>;
+ dispatch: (params: LifecycleDispatchParams) => Promise<void>;
dispatchBeforeToolCall: (
event: Omit<ToolCallHookEvent, 'mock' | 'operationId'>,
) => Promise<ToolCallMockResult | null>;