π€― 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
β¨ feat(agent-runtime): server callSubAgent async suspend/resume (#15481)
Arvin Xu04700bed52fe
diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.tsindex c700f561634..4b411fd5b59 100644--- a/packages/agent-runtime/src/core/runtime.ts+++ b/packages/agent-runtime/src/core/runtime.ts@@ -18,6 +18,7 @@ import type {ToolsCalling,Usage,} from '../types';+import { isBlockedStatus } from '../utils/status';/*** Simplified Agent Runtime - The "Engine" that executes instructions from an "Agent" (Brain).@@ -199,7 +200,7 @@ export class AgentRuntime {}// Stop execution if blocked- if (currentState.status === 'waiting_for_human' || currentState.status === 'interrupted') {+ if (isBlockedStatus(currentState.status)) {break;}}@@ -216,12 +217,10 @@ export class AgentRuntime {return {events: allEvents,newState: currentState,- // When execution is blocked (waiting for human or interrupted),- // clear nextContext so the outer loop stops instead of continuing- nextContext:- currentState.status === 'waiting_for_human' || currentState.status === 'interrupted'- ? undefined- : finalNextContext,+ // When execution is blocked (waiting for human, waiting for an async+ // tool result, or interrupted), clear nextContext so the outer loop+ // stops instead of continuing+ nextContext: isBlockedStatus(currentState.status) ? undefined : finalNextContext,};} catch (error) {const errorState = structuredClone(state);diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex ffd59521314..9273285b710 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -113,7 +113,14 @@ export interface AgentState {*/securityBlacklist?: SecurityBlacklistConfig;// --- State Machine ---- status: 'idle' | 'running' | 'waiting_for_human' | 'done' | 'error' | 'interrupted';+ status:+ | 'idle'+ | 'running'+ | 'waiting_for_human'+ | 'waiting_for_async_tool'+ | 'done'+ | 'error'+ | 'interrupted';// --- Execution Tracking ---/**diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.tsindex bf56f1b1800..9e88d101666 100644--- a/packages/agent-runtime/src/utils/index.ts+++ b/packages/agent-runtime/src/utils/index.ts@@ -1,3 +1,4 @@export * from './messageSelectors';+export * from './status';export * from './stepContextComputer';export * from './tokenCounter';diff --git a/packages/agent-runtime/src/utils/status.test.ts b/packages/agent-runtime/src/utils/status.test.tsnew file mode 100644index 00000000000..c09c3912086--- /dev/null+++ b/packages/agent-runtime/src/utils/status.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import type { AgentState } from '../types/state';+import { isBlockedStatus, isParkedStatus } from './status';++const ALL_STATUSES: AgentState['status'][] = [+ 'idle',+ 'running',+ 'waiting_for_human',+ 'waiting_for_async_tool',+ 'done',+ 'error',+ 'interrupted',+];++describe('isParkedStatus', () => {+ it('is true only for the non-terminal resumable pauses', () => {+ expect(isParkedStatus('waiting_for_human')).toBe(true);+ expect(isParkedStatus('waiting_for_async_tool')).toBe(true);+ });++ it('is false for running, terminal, and interrupted', () => {+ const nonParked = ALL_STATUSES.filter(+ (s) => s !== 'waiting_for_human' && s !== 'waiting_for_async_tool',+ );+ for (const status of nonParked) expect(isParkedStatus(status)).toBe(false);+ });+});++describe('isBlockedStatus', () => {+ it('is true for parked statuses and user interrupt', () => {+ expect(isBlockedStatus('waiting_for_human')).toBe(true);+ expect(isBlockedStatus('waiting_for_async_tool')).toBe(true);+ expect(isBlockedStatus('interrupted')).toBe(true);+ });++ it('is false for idle, running, and terminal statuses', () => {+ expect(isBlockedStatus('idle')).toBe(false);+ expect(isBlockedStatus('running')).toBe(false);+ expect(isBlockedStatus('done')).toBe(false);+ expect(isBlockedStatus('error')).toBe(false);+ });+});diff --git a/packages/agent-runtime/src/utils/status.ts b/packages/agent-runtime/src/utils/status.tsnew file mode 100644index 00000000000..771d45b4bd1--- /dev/null+++ b/packages/agent-runtime/src/utils/status.ts@@ -0,0 +1,19 @@+import type { AgentState } from '../types/state';++/**+ * Parked statuses are non-terminal, resumable pauses: the operation is still+ * alive but waiting on something out-of-band β human approval+ * (`waiting_for_human`) or an async tool / sub-agent result+ * (`waiting_for_async_tool`). They are deliberately distinct from `interrupted`+ * (user cancel) and the terminal `done` / `error`, so the completion lifecycle+ * never stamps `completedAt` and the scheduler keeps treating them as active.+ */+export const isParkedStatus = (status: AgentState['status']): boolean =>+ status === 'waiting_for_human' || status === 'waiting_for_async_tool';++/**+ * Blocked statuses halt the step loop β a parked pause or a user interrupt.+ * `done` / `error` terminate through their own handling.+ */+export const isBlockedStatus = (status: AgentState['status']): boolean =>+ isParkedStatus(status) || status === 'interrupted';diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 237dcb7d85f..b267531eb8d 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -42,13 +42,20 @@ export interface RecordOperationCompletionParams {| 'interrupted'| 'max_steps'| 'cost_limit'- | 'waiting_for_human';+ | 'waiting_for_human'+ | 'waiting_for_async_tool';cost?: Record<string, unknown> | null;error?: AgentOperationError | null;interruption?: AgentOperationInterruption | null;llmCalls?: number | null;processingTimeMs?: number | null;- status: 'running' | 'waiting_for_human' | 'done' | 'error' | 'interrupted';+ status:+ | 'running'+ | 'waiting_for_human'+ | 'waiting_for_async_tool'+ | 'done'+ | 'error'+ | 'interrupted';stepCount?: number | null;toolCalls?: number | null;totalCost?: number | null;@@ -173,4 +180,25 @@ export class AgentOperationModel {return row?.seconds ?? 0;}++ /**+ * Atomically flip a parked parent op from `waiting_for_async_tool` back to+ * `running`. Returns true only for the single winner (affected === 1) so+ * concurrent sub-op completions that lose the race no-op instead of+ * double-resuming the parent.+ */+ async tryResumeFromAsyncTool(operationId: string): Promise<boolean> {+ const rows = await this.db+ .update(agentOperations)+ .set({ status: 'running' })+ .where(+ and(+ eq(agentOperations.id, operationId),+ eq(agentOperations.userId, this.userId),+ eq(agentOperations.status, 'waiting_for_async_tool'),+ ),+ )+ .returning({ id: agentOperations.id });+ return rows.length === 1;+ }}diff --git a/packages/database/src/schemas/agentOperations.ts b/packages/database/src/schemas/agentOperations.tsindex 432f8f9b24f..763372ec77d 100644--- a/packages/database/src/schemas/agentOperations.ts+++ b/packages/database/src/schemas/agentOperations.ts@@ -11,6 +11,7 @@ const operationStatuses = ['idle','running','waiting_for_human',+ 'waiting_for_async_tool','done','error','interrupted',@@ -23,6 +24,7 @@ const completionReasons = ['max_steps','cost_limit','waiting_for_human',+ 'waiting_for_async_tool',] as const;export interface AgentOperationInterruption {diff --git a/packages/openapi/src/services/responses.service.ts b/packages/openapi/src/services/responses.service.tsindex 5cee9cce26c..a2ae1dcc8dd 100644--- a/packages/openapi/src/services/responses.service.ts+++ b/packages/openapi/src/services/responses.service.ts@@ -322,7 +322,7 @@ export class ResponsesService extends BaseService {const usage = this.extractUsage(finalState);const isClientToolInterrupt =- finalState.status === 'interrupted' &&+ finalState.status === 'waiting_for_async_tool' &&finalState.interruption?.reason === 'client_tool_execution';return this.buildResponseObject({@@ -753,7 +753,7 @@ export class ResponsesService extends BaseService {// Determine if agent was interrupted for client tool executionconst isClientToolInterrupt =- finalState?.status === 'interrupted' &&+ finalState?.status === 'waiting_for_async_tool' &&finalState?.interruption?.reason === 'client_tool_execution';if (isClientToolInterrupt) {diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 079cbc9552c..f9ff178edc6 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -288,6 +288,14 @@ export interface ExecSubAgentTaskParams {parentMessageId: string;/** Parent operation ID for dispatching callAgent hooks */parentOperationId?: string;+ /**+ * When true, register the completion bridge that backfills the parent's+ * placeholder tool message with this sub-agent's result and resumes the+ * parked parent op (`waiting_for_async_tool` β running). Used by the server+ * `callSubAgent` deferred-tool path; left false for the legacy fire-and-forget+ * task dispatch.+ */+ resumeParentOnComplete?: boolean;/** Timeout in milliseconds (optional) */timeout?: number;/** Task title (shown in UI, used as thread title) */diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 1dd7f49852f..4a906449fee 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -326,6 +326,13 @@ export type BuiltinStreaming = <A = any>(props: BuiltinStreamingProps<A>) => Reaexport interface BuiltinServerRuntimeOutput {content: string;+ /**+ * When true, the tool executed a side-effect but its result is delivered+ * out-of-band later (e.g. an async sub-agent). The agent runtime parks the+ * operation instead of writing a tool_result, mirroring the client-tool+ * pause path. The deferred result is filled in by a completion bridge.+ */+ deferred?: boolean;error?: any;state?: any;success: boolean;diff --git a/src/server/agent-hono/handlers/__tests__/runStep.test.ts b/src/server/agent-hono/handlers/__tests__/runStep.test.tsindex 11db8c6f12e..ce197c2f4a7 100644--- a/src/server/agent-hono/handlers/__tests__/runStep.test.ts+++ b/src/server/agent-hono/handlers/__tests__/runStep.test.ts@@ -122,6 +122,40 @@ describe('runStep handler', () => {);});+ it('unwraps QStash `body.payload` resume/intervention fields into executeStep', async () => {+ mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: false,+ state: { cost: { total: 0 }, status: 'running', stepCount: 2 },+ success: true,+ });++ // QStash nests these under `body.payload`, not the top level.+ const { ctx } = buildContext({+ body: {+ context: { foo: 'bar' },+ operationId: 'op-1',+ payload: {+ approvedToolCall: { id: 'tc1' },+ resumeAsyncTool: true,+ toolMessageId: 'msg-1',+ },+ stepIndex: 2,+ },+ });+ await runStep(ctx);++ expect(mockExecuteStep).toHaveBeenCalledWith(+ expect.objectContaining({+ approvedToolCall: { id: 'tc1' },+ operationId: 'op-1',+ resumeAsyncTool: true,+ stepIndex: 2,+ toolMessageId: 'msg-1',+ }),+ );+ });+it('shapes the success response with status, totals and pending fields', async () => {mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });mockExecuteStep.mockResolvedValue({diff --git a/src/server/agent-hono/handlers/runStep.ts b/src/server/agent-hono/handlers/runStep.tsindex 43b528b6ed2..291d1f7419b 100644--- a/src/server/agent-hono/handlers/runStep.ts+++ b/src/server/agent-hono/handlers/runStep.ts@@ -26,6 +26,11 @@ export async function runStep(c: Context): Promise<Response> {const externalRetryCount = Number(c.req.header('upstash-retried') ?? 0) || 0;try {+ // QStash nests resume/intervention fields under `body.payload` (see+ // QStashQueueServiceImpl.scheduleMessage), while `operationId`/`stepIndex`/+ // `context` stay at the top level. Merge so both shapes work β without this+ // the QStash path reads `resumeAsyncTool`/`approvedToolCall`/β¦ as undefined+ // and never resumes a parked op. (The local queue spreads payload itself.)const {operationId,stepIndex = 0,@@ -34,8 +39,9 @@ export async function runStep(c: Context): Promise<Response> {approvedToolCall,rejectionReason,rejectAndContinue,+ resumeAsyncTool,toolMessageId,- } = body;+ } = { ...body, ...body.payload };if (!operationId) {return c.json({ error: 'operationId is required' }, 400);@@ -63,6 +69,7 @@ export async function runStep(c: Context): Promise<Response> {operationId,rejectAndContinue,rejectionReason,+ resumeAsyncTool,stepIndex,toolMessageId,});diff --git a/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.tsindex 407b8b5779a..00f80165852 100644--- a/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts+++ b/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts@@ -23,12 +23,18 @@ const STREAM_END_STATUSES = new Set<AgentState['status']>(['error','interrupted','waiting_for_human',+ 'waiting_for_async_tool',]);const hasEnteredStreamEndState = (previousStatus?: AgentState['status'],nextStatus?: AgentState['status'],-): nextStatus is 'done' | 'error' | 'interrupted' | 'waiting_for_human' => {+): nextStatus is+ | 'done'+ | 'error'+ | 'interrupted'+ | 'waiting_for_human'+ | 'waiting_for_async_tool' => {const wasStreamEnd = previousStatus ? STREAM_END_STATUSES.has(previousStatus) : false;return Boolean(nextStatus && STREAM_END_STATUSES.has(nextStatus) && !wasStreamEnd);};@@ -127,7 +133,11 @@ export class AgentRuntimeCoordinator {*/private async resolveUiMessages(state: AgentState): Promise<UIChatMessage[] | undefined> {if (!this.uiMessagesResolver) return undefined;- if (state.status === 'interrupted') return undefined;+ // `waiting_for_async_tool` is the deferred-tool pause (client tool or+ // sub-agent): the result message is written back later, so don't push a+ // premature SoT snapshot that would clobber the client's in-memory state.+ if (state.status === 'interrupted' || state.status === 'waiting_for_async_tool')+ return undefined;try {return await this.uiMessagesResolver(state);} catch (error) {diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex c9954c184b2..751d16e8159 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -85,6 +85,7 @@ import { FileService } from '@/server/services/file';import { MessageService } from '@/server/services/message';import { OnboardingService } from '@/server/services/onboarding';import {+ type ServerSubAgentRunner,type ToolExecutionResultResponse,type ToolExecutionService,} from '@/server/services/toolExecution';@@ -235,6 +236,88 @@ const buildPostProcessUrl = (ctx: Pick<RuntimeExecutorContext, 'serverDB' | 'usefileService!.getFileAccessUrl({ id: file.id, url: path });};+/**+ * Build the per-tool-call server sub-agent runner injected into the tool+ * execution context. Closes over the current tool payload + parent message so+ * the `callSubAgent` server tool can fork a child op without re-deriving the+ * message anchor (which it cannot do correctly from its own context).+ *+ * The runner creates the pending placeholder tool message that anchors the+ * isolation thread (so the UI shows a loading state and the completion bridge+ * has a message to backfill), then kicks off the child op asynchronously and+ * returns immediately. Returns `undefined` when sub-agent execution is not+ * available (no `execSubAgentTask` callback, or missing agent/topic context).+ */+const buildServerSubAgentRunner = (+ ctx: RuntimeExecutorContext,+ state: AgentState,+ chatToolPayload: ChatToolPayload,+ parentMessageId: string,+): ServerSubAgentRunner | undefined => {+ const execSubAgentTask = ctx.execSubAgentTask;+ if (!execSubAgentTask) return undefined;++ const agentId = state.metadata?.agentId;+ const topicId = ctx.topicId ?? state.metadata?.topicId;+ if (!agentId || !topicId) return undefined;++ return {+ run: async ({ agentId: targetAgentId, description, instruction, timeout }) => {+ // 1. Create the pending placeholder tool message (mirrors the normal+ // tool-message shape in call_tool) that anchors the isolation thread+ // and renders a loading state until the bridge backfills it.+ const placeholder = await ctx.messageModel.create({+ agentId,+ content: '',+ parentId: parentMessageId,+ plugin: chatToolPayload as any,+ pluginState: { status: 'pending' },+ role: 'tool',+ threadId: state.metadata?.threadId,+ tool_call_id: chatToolPayload.id,+ topicId,+ });++ // 2. Fork the child op anchored to the placeholder. `resumeParentOnComplete`+ // tells execSubAgentTask to register the completion bridge that+ // backfills this tool message and resumes the parent op.+ const result = (await execSubAgentTask({+ agentId: targetAgentId ?? agentId,+ groupId: state.metadata?.groupId ?? undefined,+ instruction,+ parentMessageId: placeholder.id,+ parentOperationId: ctx.operationId,+ resumeParentOnComplete: true,+ timeout,+ title: description,+ topicId,+ })) as { operationId?: string; success?: boolean; threadId?: string } | undefined;++ // 3. If the child op never started, no completion bridge will fire β parking+ // the parent on it would hang forever. Drop the placeholder and signal+ // `started: false` so callSubAgent surfaces an inline tool error instead.+ if (!result?.success) {+ try {+ await ctx.messageModel.deleteMessage(placeholder.id);+ } catch (error) {+ log(+ 'buildServerSubAgentRunner: failed to clean up placeholder %s: %O',+ placeholder.id,+ error,+ );+ }+ return { started: false, subOperationId: result?.operationId, threadId: '' };+ }++ return {+ started: true,+ subOperationId: result?.operationId,+ threadId: result?.threadId ?? '',+ };+ },+ };+};+const shouldRetryLLM = (kind: LLMErrorKind, attempt: number, maxRetries: number) =>kind === 'retry' && attempt <= maxRetries;@@ -1923,7 +2006,7 @@ export const createRuntimeExecutors = (const newState = structuredClone(state);newState.lastModified = new Date().toISOString();- newState.status = 'interrupted';+ newState.status = 'waiting_for_async_tool';newState.interruption = {canResume: true,interruptedAt: new Date().toISOString(),@@ -2061,6 +2144,7 @@ export const createRuntimeExecutors = (activeDeviceId: state.metadata?.activeDeviceId,agentId: state.metadata?.agentId,documentId: state.metadata?.documentId,+ execSubAgentTask: ctx.execSubAgentTask,executionTimeoutMs: timeoutMs,groupId: state.metadata?.groupId,memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,@@ -2078,6 +2162,12 @@ export const createRuntimeExecutors = (scope: state.metadata?.scope,serverDB: ctx.serverDB,skipResultTruncation: true,+ subAgent: buildServerSubAgentRunner(+ ctx,+ state,+ chatToolPayload,+ payload.parentMessageId,+ ),taskId: state.metadata?.taskId,threadId: state.metadata?.threadId,toolCallId: chatToolPayload.id,@@ -2095,6 +2185,42 @@ export const createRuntimeExecutors = ();}+ // Deferred tool (e.g. async sub-agent): the executor performed its+ // side-effect and created a pending placeholder; the real result is+ // delivered out-of-band later by a completion bridge. Park like a+ // client tool β surface the pending call, hold it in pendingToolsCalling,+ // and do not write a tool_result now.+ if (execution.result.deferred) {+ log(`[${operationLogId}] Tool ${toolName} deferred; parking for async result`);+ await streamManager.publishStreamChunk(operationId, stepIndex, {+ chunkType: 'tools_calling',+ toolsCalling: [chatToolPayload] as any,+ });+ executeToolSpan.setAttributes(+ buildExecuteToolResultAttributes({ attempts: execution.attempts, success: true }),+ );+ const newState = structuredClone(state);+ newState.lastModified = new Date().toISOString();+ newState.status = 'waiting_for_async_tool';+ newState.interruption = {+ canResume: true,+ interruptedAt: new Date().toISOString(),+ reason: 'async_tool',+ };+ newState.pendingToolsCalling = [chatToolPayload];+ return {+ events: [+ {+ canResume: true,+ interruptedAt: new Date().toISOString(),+ reason: 'async_tool',+ type: 'interrupted',+ },+ ],+ newState,+ };+ }+const executionResult = await archiveRuntimeToolResult(execution.result, {agentId: state.metadata?.agentId,identifier: chatToolPayload.identifier,@@ -2417,7 +2543,7 @@ export const createRuntimeExecutors = (const newState = structuredClone(state);newState.lastModified = new Date().toISOString();- newState.status = 'interrupted';+ newState.status = 'waiting_for_async_tool';newState.interruption = {canResume: true,interruptedAt: new Date().toISOString(),@@ -2441,6 +2567,9 @@ export const createRuntimeExecutors = (// Track all tool message IDs created during executionconst toolMessageIds: string[] = [];const toolResults: any[] = [];+ // Deferred (async) tools whose result is delivered out-of-band later;+ // collected here so the batch parks for them after server tools finish.+ const deferredTools: ChatToolPayload[] = [];// Execute server tools concurrently (skip client tools in mixed batch)const toolsToExecute = serverTools.length > 0 ? serverTools : toolsCalling;@@ -2593,6 +2722,7 @@ export const createRuntimeExecutors = (activeDeviceId: state.metadata?.activeDeviceId,agentId: state.metadata?.agentId,documentId: state.metadata?.documentId,+ execSubAgentTask: ctx.execSubAgentTask,executionTimeoutMs: timeoutMs,groupId: state.metadata?.groupId,memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,@@ -2601,6 +2731,12 @@ export const createRuntimeExecutors = (scope: state.metadata?.scope,serverDB: ctx.serverDB,skipResultTruncation: true,+ subAgent: buildServerSubAgentRunner(+ ctx,+ state,+ chatToolPayload,+ payload.parentMessageId,+ ),taskId: state.metadata?.taskId,threadId: state.metadata?.threadId,toolCallId: chatToolPayload.id,@@ -2618,6 +2754,18 @@ export const createRuntimeExecutors = ();}+ // Deferred (async) tool: executor created a pending placeholder and+ // the real result arrives out-of-band. Skip the tool_result write;+ // the batch parks for it after all server tools settle.+ if (execution.result.deferred) {+ log(`[${operationLogId}] Tool ${toolName} deferred; will park after batch`);+ deferredTools.push(chatToolPayload);+ batchExecuteToolSpan.setAttributes(+ buildExecuteToolResultAttributes({ attempts: execution.attempts, success: true }),+ );+ return;+ }+const executionResult = await archiveRuntimeToolResult(execution.result, {agentId: state.metadata?.agentId,identifier: chatToolPayload.identifier,@@ -2872,24 +3020,31 @@ export const createRuntimeExecutors = (// Get the last tool message ID as parentMessageId for next LLM callconst lastToolMessageId = toolMessageIds.at(-1);- // If there are remaining client tools in a mixed batch, interrupt after server tools- if (clientTools.length > 0) {+ // Park if any tools still owe an out-of-band result: client tools (run on+ // the client) and/or deferred async tools (e.g. sub-agents). The operation+ // resumes once every pending tool's result is delivered.+ const pendingTools = [...deferredTools, ...clientTools];+ if (pendingTools.length > 0) {+ // Prefer the async-tool reason when any deferred tool is present; the+ // individual pending payloads still carry their own identity for the+ // resume gate.+ const pauseReason = deferredTools.length > 0 ? 'async_tool' : 'client_tool_execution';log(- `[${operationLogId}][call_tools_batch] Mixed batch: ${serverTools.length} server tools done, pausing for ${clientTools.length} client tools`,+ `[${operationLogId}][call_tools_batch] Pausing after ${serverTools.length} server tools: ${deferredTools.length} deferred + ${clientTools.length} client`,);await streamManager.publishStreamChunk(operationId, stepIndex, {chunkType: 'tools_calling',- toolsCalling: clientTools as any,+ toolsCalling: pendingTools as any,});- newState.status = 'interrupted';+ newState.status = 'waiting_for_async_tool';newState.interruption = {canResume: true,interruptedAt: new Date().toISOString(),- reason: 'client_tool_execution',+ reason: pauseReason,};- newState.pendingToolsCalling = clientTools;+ newState.pendingToolsCalling = pendingTools;return {events: [@@ -2897,7 +3052,7 @@ export const createRuntimeExecutors = ({canResume: true,interruptedAt: new Date().toISOString(),- reason: 'client_tool_execution',+ reason: pauseReason,type: 'interrupted',},],diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.tsnew file mode 100644index 00000000000..233ca13bd12--- /dev/null+++ b/src/server/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts@@ -0,0 +1,248 @@+// @vitest-environment node+/**+ * Integration test for the server `callSubAgent` async suspend/resume flow.+ *+ * Verifies the full deferred-tool lifecycle end-to-end on the in-memory runtime:+ * 1. Parent op LLM emits a `lobe-agent____callSubAgent` tool call.+ * 2. The real server executor parks the parent (`waiting_for_async_tool`),+ * creates a pending placeholder tool message, and forks a child op.+ * 3. The child op runs independently and completes.+ * 4. The completion bridge backfills the placeholder tool message with the+ * sub-agent's answer and resumes the parent.+ * 5. The parent op runs one more LLM step and reaches `done`.+ */+import { type LobeChatDatabase } from '@lobechat/database';+import { agentOperations, agents, messages } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import OpenAI from 'openai';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { inMemoryAgentStateManager } from '@/server/modules/AgentRuntime/InMemoryAgentStateManager';+import { inMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';++import { aiAgentRouter } from '../../../aiAgent';+import { cleanupTestUser, createTestUser } from '../setup';+import { createMockResponsesStream, waitForOperationComplete } from './helpers';++process.env.OPENAI_API_KEY = 'sk-test-fake-api-key-for-testing';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ getFullFileUrl: vi.fn().mockImplementation((path: string) => (path ? `/files${path}` : null)),+ })),+}));++let mockResponsesCreate: any;+let serverDB: LobeChatDatabase;+let userId: string;+let testAgentId: string;++const SUB_AGENT_ANSWER = 'The sub-agent researched the topic and found the answer is 42.';+const PARENT_FINAL = 'Based on the sub-agent result, the final answer is 42.';++const createTestContext = () => ({ jwtPayload: { userId }, userId });++/** Mock parent first step: a single `callSubAgent` tool call. */+const createCallSubAgentResponse = () => {+ const responseId = `resp_parent_${Date.now()}`;+ const msgItemId = `msg_parent_${Date.now()}`;+ const callId = `call_subagent_1`;+ const fnCall = {+ arguments: JSON.stringify({+ description: 'Research the answer',+ instruction: 'Find the answer to the ultimate question.',+ }),+ call_id: callId,+ name: 'lobe-agent____callSubAgent',+ type: 'function_call',+ };++ const chunks = [+ {+ response: {+ created_at: Math.floor(Date.now() / 1000),+ id: responseId,+ model: 'gpt-5-pro',+ object: 'response',+ output: [],+ status: 'in_progress',+ },+ type: 'response.created',+ },+ {+ item: {+ content: [],+ id: msgItemId,+ role: 'assistant',+ status: 'in_progress',+ type: 'message',+ },+ output_index: 0,+ type: 'response.output_item.added',+ },+ {+ content_index: 0,+ delta: 'Let me delegate this to a sub-agent.',+ item_id: msgItemId,+ output_index: 0,+ type: 'response.output_text.delta',+ },+ { item: fnCall, output_index: 1, type: 'response.output_item.added' },+ {+ response: {+ created_at: Math.floor(Date.now() / 1000),+ id: responseId,+ model: 'gpt-5-pro',+ object: 'response',+ output: [+ {+ content: [{ text: 'Let me delegate this to a sub-agent.', type: 'output_text' }],+ id: msgItemId,+ role: 'assistant',+ status: 'completed',+ type: 'message',+ },+ fnCall,+ ],+ status: 'completed',+ usage: { input_tokens: 30, output_tokens: 20, total_tokens: 50 },+ },+ type: 'response.completed',+ },+ ];++ return createMockResponsesStream(chunks);+};++/** Mock a plain final text response (no tool calls). */+const createFinalTextResponse = (content: string) => {+ const responseId = `resp_final_${Date.now()}_${Math.round(content.length)}`;+ const msgItemId = `msg_final_${Date.now()}_${Math.round(content.length)}`;++ const chunks = [+ {+ response: {+ created_at: Math.floor(Date.now() / 1000),+ id: responseId,+ model: 'gpt-5-pro',+ object: 'response',+ output: [],+ status: 'in_progress',+ },+ type: 'response.created',+ },+ {+ content_index: 0,+ delta: content,+ item_id: msgItemId,+ output_index: 0,+ type: 'response.output_text.delta',+ },+ {+ response: {+ created_at: Math.floor(Date.now() / 1000),+ id: responseId,+ model: 'gpt-5-pro',+ object: 'response',+ output: [+ {+ content: [{ text: content, type: 'output_text' }],+ id: msgItemId,+ role: 'assistant',+ status: 'completed',+ type: 'message',+ },+ ],+ status: 'completed',+ usage: { input_tokens: 40, output_tokens: 20, total_tokens: 60 },+ },+ type: 'response.completed',+ },+ ];++ return createMockResponsesStream(chunks);+};++beforeEach(async () => {+ serverDB = await getTestDB();+ testDB = serverDB;+ userId = await createTestUser(serverDB);++ const [agent] = await serverDB+ .insert(agents)+ .values({+ chatConfig: {},+ model: 'gpt-5-pro',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a supervisor that can delegate work to sub-agents.',+ title: 'Supervisor',+ userId,+ })+ .returning();+ testAgentId = agent.id;++ mockResponsesCreate = vi.spyOn(OpenAI.Responses.prototype, 'create');+});++afterEach(async () => {+ await cleanupTestUser(serverDB, userId);+ vi.clearAllMocks();+ vi.restoreAllMocks();+ inMemoryAgentStateManager.clear();+ inMemoryStreamEventManager.clear();+});++describe('Server callSubAgent suspend/resume', () => {+ it('parks the parent, runs the sub-op, backfills the tool message and resumes', async () => {+ // 1: parent emits callSubAgent 2: sub-op final answer 3: parent resume final+ let callCount = 0;+ mockResponsesCreate.mockImplementation(() => {+ callCount++;+ if (callCount === 1) return Promise.resolve(createCallSubAgentResponse() as any);+ if (callCount === 2) return Promise.resolve(createFinalTextResponse(SUB_AGENT_ANSWER) as any);+ return Promise.resolve(createFinalTextResponse(PARENT_FINAL) as any);+ });++ const caller = aiAgentRouter.createCaller(createTestContext());++ const createResult = await caller.execAgent({+ agentId: testAgentId,+ prompt: 'Please research the ultimate question and report back.',+ });+ expect(createResult.success).toBe(true);++ const finalState = await waitForOperationComplete(+ inMemoryAgentStateManager,+ createResult.operationId,+ { maxWaitTime: 20_000 },+ );++ // Parent resumed and completed+ expect(finalState.status).toBe('done');+ expect(finalState.pendingToolsCalling ?? []).toHaveLength(0);++ // Three LLM calls: parent-initial, sub-op, parent-resume+ expect(mockResponsesCreate).toHaveBeenCalledTimes(3);++ // A child op was spawned and reconciled to the parent+ const childOps = await serverDB+ .select()+ .from(agentOperations)+ .where(eq(agentOperations.parentOperationId, createResult.operationId));+ expect(childOps.length).toBeGreaterThanOrEqual(1);++ // The placeholder tool message was backfilled with the sub-agent's answer+ const allMessages = await serverDB.select().from(messages).where(eq(messages.userId, userId));+ const subAgentToolMessage = allMessages.find(+ (m) => m.role === 'tool' && m.content === SUB_AGENT_ANSWER,+ );+ expect(subAgentToolMessage).toBeDefined();+ });+});diff --git a/src/server/services/agentRuntime/AgentRuntimeService.test.ts b/src/server/services/agentRuntime/AgentRuntimeService.test.tsindex a79c77ede6f..2d5ef36bf2c 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.test.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.test.ts@@ -5,6 +5,8 @@ import { getModelPropertyWithFallback } from '@lobechat/model-runtime';import type * as ModelBankModule from 'model-bank';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { AgentRuntimeService } from './AgentRuntimeService';import { hookDispatcher } from './hooks';import {@@ -100,6 +102,14 @@ vi.mock('@lobechat/agent-runtime', () => ({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', () => ({@@ -1535,4 +1545,84 @@ describe('AgentRuntimeService', () => {expect(result).toBeUndefined();});});++ describe('tryResumeParentFromAsyncTool', () => {+ const parentOpId = 'parent-op-async';++ const fulfilledPlugin = { id: 'msg-tc1', state: { status: 'completed' }, toolCallId: 'tc1' };++ const stubFulfilled = () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 3,+ });+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn().mockResolvedValue(fulfilledPlugin) },+ };+ (service as any).messageModel.findById = vi.fn().mockResolvedValue({ content: 'answer' });+ };++ it('wins the CAS and schedules the resume step when all pending tools are fulfilled', async () => {+ stubFulfilled();+ const casSpy = vi+ .spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool')+ .mockResolvedValue(true);++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(true);+ expect(casSpy).toHaveBeenCalledWith(parentOpId);+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ operationId: parentOpId,+ payload: { resumeAsyncTool: true },+ priority: 'high',+ stepIndex: 3,+ }),+ );+ });++ it('holds (no CAS, no schedule) when a pending tool is not yet fulfilled', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 1,+ });+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },+ };+ const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(false);+ expect(casSpy).not.toHaveBeenCalled();+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('does not schedule when it loses the CAS to a concurrent sibling', async () => {+ stubFulfilled();+ vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool').mockResolvedValue(false);++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('skips when the parent is no longer parked', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [],+ status: 'running',+ stepCount: 1,+ });+ const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(false);+ expect(casSpy).not.toHaveBeenCalled();+ });+ });});diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex 21a39792a7e..153d235b817 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -4,9 +4,15 @@ import type {AgentState,GeneralAgentConfig,} from '@lobechat/agent-runtime';-import { AgentRuntime, findInMessages, GeneralChatAgent } from '@lobechat/agent-runtime';+import {+ AgentRuntime,+ findInMessages,+ GeneralChatAgent,+ isParkedStatus,+} from '@lobechat/agent-runtime';import type { ISnapshotStore } from '@lobechat/agent-tracing';import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';+import { parse } from '@lobechat/conversation-flow';import { getModelPropertyWithFallback } from '@lobechat/model-runtime';import {context as otelContext,@@ -19,10 +25,15 @@ import {invokeAgentSpanName,tracer as agentRuntimeTracer,} from '@lobechat/observability-otel/modules/agent-runtime';-import { type ExecSubAgentTaskParams, type UIChatMessage } from '@lobechat/types';+import {+ type ChatToolPayload,+ type ExecSubAgentTaskParams,+ type UIChatMessage,+} from '@lobechat/types';import debug from 'debug';import urlJoin from 'url-join';+import { AgentOperationModel } from '@/database/models/agentOperation';import { MessageModel } from '@/database/models/message';import { type LobeChatDatabase } from '@/database/type';import { appEnv } from '@/envs/app';@@ -36,6 +47,7 @@ import {import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';+import { FileService } from '@/server/services/file';import { mcpService } from '@/server/services/mcp';import { MessageService } from '@/server/services/message';import { QueueService } from '@/server/services/queue';@@ -214,8 +226,12 @@ export class AgentRuntimeService {const impl = this.queueService.getImpl();if (impl instanceof LocalQueueServiceImpl) {log('Setting up local execution callback');- impl.setExecutionCallback(async (operationId, stepIndex, context) => {- await this.executeStep({ context, operationId, stepIndex });+ impl.setExecutionCallback(async (operationId, stepIndex, context, payload) => {+ // Mirror the QStash path where payload fields (approvedToolCall,+ // toolMessageId, resumeAsyncTool, β¦) ride the request body into+ // executeStep. Without this spread, local/in-memory resumes silently+ // lose their intervention/resume signal.+ await this.executeStep({ context, operationId, stepIndex, ...payload });});}}@@ -501,6 +517,7 @@ export class AgentRuntimeService {approvedToolCall,rejectionReason,rejectAndContinue,+ resumeAsyncTool,toolMessageId,externalRetryCount = 0,} = params;@@ -716,6 +733,30 @@ export class AgentRuntimeService {currentContext = interventionResult.nextContext;}+ // Resume from a parked async-tool wait (server sub-agent completion+ // bridge). Every deferred tool has delivered its result by now, so clear+ // the pending set, refresh messages from the DB (to pick up the tool+ // results written out-of-band), and re-enter the LLM with them.+ if (resumeAsyncTool && currentState.status === 'waiting_for_async_tool') {+ const refreshed = await this.refreshMessagesFromDB(currentState);+ currentState = structuredClone(currentState);+ currentState.messages = refreshed;+ currentState.pendingToolsCalling = [];+ currentState.status = 'running';+ currentState.interruption = undefined;+ currentState.lastModified = new Date().toISOString();+ currentContext = {+ payload: { parentMessageId: refreshed.at(-1)?.id },+ phase: 'user_input',+ } as AgentRuntimeContext;+ log(+ '[%s][%d] Resuming from async tool with %d messages',+ operationId,+ stepIndex,+ refreshed.length,+ );+ }+// Pre-step computation: extract device context from DB messages// Follows front-end computeStepContext pattern β computed at step boundary, not inside executorsif (!currentState.metadata?.activeDeviceId) {@@ -1187,7 +1228,7 @@ export class AgentRuntimeService {},executionHistory: executionHistory?.slice(0, historyLimit),hasError: currentState.status === 'error',- isActive: ['running', 'waiting_for_human'].includes(currentState.status),+ isActive: currentState.status === 'running' || isParkedStatus(currentState.status),isCompleted: currentState.status === 'done',metadata: operationMetadata,needsHumanInput: currentState.status === 'waiting_for_human',@@ -1446,6 +1487,116 @@ export class AgentRuntimeService {}}+ /**+ * Completion-bridge entry point for async sub-agent tools.+ *+ * Called once per sub-op completion (the bridge already backfilled that+ * sub-op's tool message). Implements the K=N barrier + single-fire resume:+ *+ * 1. The parent must still be parked (`waiting_for_async_tool`).+ * 2. Every tool in this turn's `pendingToolsCalling` must be fulfilled β+ * the true gate, since the LLM can only continue once every tool_result+ * message row is present (covers mixed sub-agent + client-tool batches).+ * 3. Atomically claim the resume via a status CAS; only the winner proceeds.+ * 4. Schedule the parent's next step (`resumeAsyncTool`), which re-enters+ * the LLM with the refreshed tool results.+ *+ * Returns true only for the CAS winner that scheduled the resume.+ */+ async tryResumeParentFromAsyncTool(params: { parentOperationId: string }): Promise<boolean> {+ const { parentOperationId } = params;++ const state = await this.coordinator.loadAgentState(parentOperationId);+ if (!state || state.status !== 'waiting_for_async_tool') return false;++ const pending = (state.pendingToolsCalling ?? []) as ChatToolPayload[];+ if (pending.length === 0) return false;++ // Barrier: every pending tool must have a fulfilled tool_result message.+ const allFulfilled = await this.allPendingToolsFulfilled(pending);+ if (!allFulfilled) {+ log('[%s] async-tool barrier not yet satisfied, holding', parentOperationId);+ return false;+ }++ // Single-fire guard: only one concurrent completion flips the op.+ const won = await new AgentOperationModel(this.serverDB, this.userId).tryResumeFromAsyncTool(+ parentOperationId,+ );+ if (!won) {+ log('[%s] lost async-tool resume CAS, no-op', parentOperationId);+ return false;+ }++ log('[%s] won async-tool resume CAS, scheduling step %d', parentOperationId, state.stepCount);++ if (this.queueService) {+ await this.queueService.scheduleMessage({+ context: undefined,+ delay: 100,+ endpoint: `${this.baseURL}/run`,+ operationId: parentOperationId,+ payload: { resumeAsyncTool: true },+ priority: 'high',+ stepIndex: state.stepCount,+ });+ } else {+ log('[%s] queue service disabled, skipping async-tool resume schedule', parentOperationId);+ }++ return true;+ }++ /**+ * Whether every pending tool call has a fulfilled tool_result message β i.e.+ * a tool message exists for its `tool_call_id` with non-empty content or a+ * terminal pluginState. Looks up by `tool_call_id` (plugin id === message id).+ */+ private async allPendingToolsFulfilled(pending: ChatToolPayload[]): Promise<boolean> {+ for (const tc of pending) {+ const plugin = await this.serverDB.query.messagePlugins.findFirst({+ where: (mp, { eq }) => eq(mp.toolCallId, tc.id),+ });+ if (!plugin) return false;++ const message = await this.messageModel.findById(plugin.id);+ const pluginState = plugin.state as { status?: string } | null;+ const fulfilled =+ (!!message?.content && message.content.length > 0) ||+ pluginState?.status === 'completed' ||+ pluginState?.status === 'error';+ if (!fulfilled) return false;+ }+ return true;+ }++ /**+ * Reload the conversation messages from the database and flatten them for the+ * runtime. Used when resuming a parked op so the next LLM step sees tool+ * results written out-of-band (e.g. by a sub-agent completion bridge).+ */+ private async refreshMessagesFromDB(state: AgentState): Promise<AgentState['messages']> {+ let postProcessUrl: ((path: string | null) => Promise<string>) | undefined;+ try {+ const fileService = new FileService(this.serverDB, this.userId);+ postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);+ } catch {+ postProcessUrl = undefined;+ }++ const dbMessages = await this.messageModel.query(+ {+ agentId: state.metadata?.agentId,+ threadId: state.metadata?.threadId,+ topicId: state.metadata?.topicId,+ },+ { postProcessUrl },+ );++ const { flatList } = parse(dbMessages);+ return flatList as AgentState['messages'];+ }+/*** Create Agent Runtime instance*/@@ -1589,6 +1740,9 @@ export class AgentRuntimeService {// Needs human interventionif (state.status === 'waiting_for_human') return false;+ // Parked waiting for an async tool result (client tool / sub-agent)+ if (state.status === 'waiting_for_async_tool') return false;+// Error occurredif (state.status === 'error') return false;@@ -1653,6 +1807,7 @@ export class AgentRuntimeService {if (state.status === 'error') return 'error';if (state.status === 'interrupted') return 'interrupted';if (state.status === 'waiting_for_human') return 'waiting_for_human';+ if (state.status === 'waiting_for_async_tool') return 'waiting_for_async_tool';if (state.maxSteps && state.stepCount >= state.maxSteps) return 'max_steps';if (state.costLimit && state.cost?.total >= state.costLimit.maxTotalCost) return 'cost_limit';return 'done';@@ -1726,9 +1881,11 @@ export class AgentRuntimeService {break;}- // Check if human intervention is needed- if (state.status === 'waiting_for_human') {- log('[%s] Sync execution paused: waiting for human intervention', operationId);+ // Parked on a pause (human intervention or an async tool / sub-agent+ // result) β the result is delivered out-of-band, so sync execution+ // can't resume it+ if (isParkedStatus(state.status)) {+ log('[%s] Sync execution paused: %s', operationId, state.status);break;}diff --git a/src/server/services/agentRuntime/CompletionLifecycle.ts b/src/server/services/agentRuntime/CompletionLifecycle.tsindex 89f3490bbd7..3676018aa9c 100644--- a/src/server/services/agentRuntime/CompletionLifecycle.ts+++ b/src/server/services/agentRuntime/CompletionLifecycle.ts@@ -1,3 +1,4 @@+import { isParkedStatus } from '@lobechat/agent-runtime';import debug from 'debug';import {@@ -66,10 +67,12 @@ export class CompletionLifecycle {/*** Map a completion reason to the terminal `agent_operations.status` value.- * `waiting_for_human` keeps `status='waiting_for_human'` so analytics can- * distinguish paused ops from terminal ones.+ * `waiting_for_human` / `waiting_for_async_tool` keep their own status so+ * analytics can distinguish paused ops from terminal ones.*/- private statusForReason(reason: string): 'done' | 'error' | 'interrupted' | 'waiting_for_human' {+ private statusForReason(+ reason: string,+ ): 'done' | 'error' | 'interrupted' | 'waiting_for_human' | 'waiting_for_async_tool' {switch (reason) {case 'error': {return 'error';@@ -80,6 +83,9 @@ export class CompletionLifecycle {case 'waiting_for_human': {return 'waiting_for_human';}+ case 'waiting_for_async_tool': {+ return 'waiting_for_async_tool';+ }default: {return 'done';}@@ -93,7 +99,10 @@ export class CompletionLifecycle {*/private async persistCompletion(operationId: string, state: any, reason: string): Promise<void> {const completionReason: any =- reason === 'max_steps' || reason === 'cost_limit' || reason === 'waiting_for_human'+ reason === 'max_steps' ||+ reason === 'cost_limit' ||+ reason === 'waiting_for_human' ||+ reason === 'waiting_for_async_tool'? reason: this.statusForReason(reason);@@ -108,11 +117,10 @@ export class CompletionLifecycle {: null;const status = this.statusForReason(reason);- // `waiting_for_human` is a pause, not a true terminal state β leave- // completedAt null so analytics doesn't read a paused op as completed.- // The next dispatchHooks call (when the human resumes and the op truly- // ends) will overwrite both fields.- const completedAt = status === 'waiting_for_human' ? undefined : new Date();+ // Parked statuses are pauses, not true terminal states β leave completedAt+ // null so analytics doesn't read a paused op as completed. The next+ // dispatchHooks call (when the op resumes and truly ends) overwrites both.+ const completedAt = isParkedStatus(status) ? undefined : new Date();try {await this.agentOperationModel.recordCompletion(operationId, {@@ -258,6 +266,14 @@ export class CompletionLifecycle {* Fire-and-forget; always unregisters the operation from the dispatcher.*/async dispatchHooks(operationId: string, state: any, reason: string): Promise<void> {+ // `waiting_for_async_tool` parks the SAME operation: it persists the parked+ // status (the async-tool resume CAS reads it) but must NOT fire `onComplete`+ // or unregister hooks β the op resumes under this same id and reaches its+ // real terminal state later, which is when consumers should be notified.+ // (`waiting_for_human` differs: its resume runs under a NEW operationId, so+ // firing + unregistering on the park is correct there.)+ const isAsyncToolPark = reason === 'waiting_for_async_tool';+try {const { event, metadata } = this.buildLifecycleEvent(operationId, state, reason);@@ -265,6 +281,8 @@ export class CompletionLifecycle {// downstream consumers see the row in its terminal shape.await this.persistCompletion(operationId, state, reason);+ if (isAsyncToolPark) return;+await hookDispatcher.dispatch(operationId, 'onComplete', event, metadata._hooks);if (reason === 'error') {@@ -293,7 +311,9 @@ export class CompletionLifecycle {} catch (error) {log('[%s] Hook dispatch error (non-fatal): %O', operationId, error);} finally {- hookDispatcher.unregister(operationId);+ // Keep hooks registered across an async-tool park so the eventual resume+ // (same operationId) can still fire onComplete/onError.+ if (!isAsyncToolPark) hookDispatcher.unregister(operationId);}}diff --git a/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 38f84f64993..dc3a0db1923 100644--- a/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -1,7 +1,8 @@// @vitest-environment node-import { describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { CompletionLifecycle } from '../CompletionLifecycle';+import { hookDispatcher } from '../hooks';const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');@@ -195,3 +196,40 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {expect(event.agentId).toBe('a');});});++describe('CompletionLifecycle.dispatchHooks β async-tool park', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ const parkedState = {+ metadata: { agentId: 'a', _hooks: [] },+ status: 'waiting_for_async_tool',+ };++ it('persists the parked status but does NOT fire onComplete or unregister hooks', async () => {+ const lifecycle = buildLifecycle();+ const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});++ await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_async_tool');++ expect(persistSpy).toHaveBeenCalledWith('op-1', parkedState, 'waiting_for_async_tool');+ expect(dispatchSpy).not.toHaveBeenCalled();+ expect(unregisterSpy).not.toHaveBeenCalled();+ });++ it('fires onComplete and unregisters on a terminal completion', async () => {+ const lifecycle = buildLifecycle();+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});++ const doneState = { metadata: { agentId: 'a', _hooks: [] }, status: 'done' };+ await lifecycle.dispatchHooks('op-1', doneState, 'done');++ expect(dispatchSpy).toHaveBeenCalledWith('op-1', 'onComplete', expect.anything(), []);+ expect(unregisterSpy).toHaveBeenCalledWith('op-1');+ });+});diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.tsindex faeabcc240e..df217b90378 100644--- a/src/server/services/agentRuntime/types.ts+++ b/src/server/services/agentRuntime/types.ts@@ -113,7 +113,8 @@ export type StepCompletionReason =| 'interrupted'| 'max_steps'| 'cost_limit'- | 'waiting_for_human';+ | 'waiting_for_human'+ | 'waiting_for_async_tool';// ==================== Execution Params ====================@@ -130,6 +131,12 @@ export interface AgentExecutionParams {*/rejectAndContinue?: boolean;rejectionReason?: string;+ /**+ * Resume a `waiting_for_async_tool` op after its deferred tools (e.g. server+ * sub-agents) have all delivered results. Scheduled by the completion bridge+ * via `tryResumeParentFromAsyncTool`.+ */+ resumeAsyncTool?: boolean;stepIndex: number;/** ID of the pending tool message targeted by the intervention. */toolMessageId?: string;diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 43a9b0bfaed..a2fa548ae52 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -2499,8 +2499,16 @@ export class AiAgentService {* 3. Store operationId in Thread metadata*/async execSubAgentTask(params: ExecSubAgentTaskParams): Promise<ExecSubAgentTaskResult> {- const { groupId, topicId, parentMessageId, agentId, instruction, title, parentOperationId } =- params;+ const {+ groupId,+ topicId,+ parentMessageId,+ agentId,+ instruction,+ title,+ parentOperationId,+ resumeParentOnComplete,+ } = params;log('execSubAgentTask: agentId=%s, groupId=%s, topicId=%s, instruction=%s',@@ -2547,6 +2555,17 @@ export class AiAgentService {// 3. Create hooks for updating Thread metadata and task messageconst threadHooks = this.createThreadHooks(thread.id, startedAt, parentMessageId);+ // For the deferred-tool path, also register the completion bridge that+ // backfills the parent's placeholder tool message and resumes the parked+ // parent op once the whole batch is done. Registered last so its+ // tool-message backfill (content + pluginState) is the final write.+ const hooks =+ resumeParentOnComplete && parentOperationId+ ? [+ ...threadHooks,+ this.createSubAgentBridgeHook(parentOperationId, parentMessageId, thread.id),+ ]+ : threadHooks;// Inherit parent op's trigger so sub-agent rows stay attributable to the// original entry point (chat / bot / cli / eval / β¦). Lookup is best-effort@@ -2570,7 +2589,7 @@ export class AiAgentService {agentId,appContext: { groupId, threadId: thread.id, topicId },autoStart: true,- hooks: threadHooks,+ hooks,parentOperationId,prompt: instruction,trigger: inheritedTrigger,@@ -2888,6 +2907,74 @@ export class AiAgentService {];}+ /**+ * Completion bridge for the server `callSubAgent` deferred-tool path.+ *+ * Fires on the sub-op's completion (success or failure). It:+ * 1. Backfills the parent's placeholder tool message with the sub-agent's+ * final answer (success) or an error note (failure), plus pluginState so+ * the UI render can resolve the isolation thread.+ * 2. Asks the runtime to resume the parent: barrier-check that every pending+ * tool in this turn is now fulfilled, atomically claim the resume (CAS),+ * and schedule the next parent step. Concurrent sibling completions that+ * lose the CAS are no-ops.+ */+ private createSubAgentBridgeHook(+ parentOperationId: string,+ toolMessageId: string,+ threadId: string,+ ): AgentHook {+ return {+ handler: async (event) => {+ const finalState = event.finalState;+ const failed = event.reason === 'error' || event.reason === 'interrupted';++ // 1. Backfill the placeholder tool message with the result+ try {+ const lastAssistant = finalState?.messages+ ?.slice()+ .reverse()+ .find((m: { content?: string; role: string }) => m.role === 'assistant');++ const content = failed+ ? `Sub-agent did not complete (${event.reason}).`+ : lastAssistant?.content || 'Sub-agent completed without a textual answer.';++ await this.messageModel.updateToolMessage(toolMessageId, {+ content,+ pluginError: failed ? formatErrorForMetadata(finalState?.error) : undefined,+ pluginState: {+ model: finalState?.modelRuntimeConfig?.model,+ status: failed ? 'error' : 'completed',+ threadId,+ totalToolCalls: finalState?.usage?.tools?.totalCalls,+ totalTokens: this.calculateTotalTokens(finalState?.usage),+ },+ });+ } catch (error) {+ console.error(+ 'Sub-agent bridge: failed to backfill tool message %s: %O',+ toolMessageId,+ error,+ );+ }++ // 2. Barrier + CAS + resume the parent op+ try {+ await this.agentRuntimeService.tryResumeParentFromAsyncTool({ parentOperationId });+ } catch (error) {+ console.error(+ 'Sub-agent bridge: failed to resume parent %s: %O',+ parentOperationId,+ error,+ );+ }+ },+ id: 'sub-agent-bridge',+ type: 'onComplete' as const,+ };+ }+/*** Calculate total tokens from AgentState usage object* AgentState.usage is of type Usage from @lobechat/agent-runtimediff --git a/src/server/services/queue/impls/local.ts b/src/server/services/queue/impls/local.tsindex aab2628bd81..1616a6de153 100644--- a/src/server/services/queue/impls/local.ts+++ b/src/server/services/queue/impls/local.ts@@ -13,6 +13,7 @@ export type LocalExecutionCallback = (operationId: string,stepIndex: number,context: any,+ payload?: any,) => Promise<void>;/**@@ -37,7 +38,7 @@ export class LocalQueueServiceImpl implements QueueServiceImpl {}async scheduleMessage(message: QueueMessage): Promise<string> {- const { operationId, stepIndex, context, delay = 50 } = message;+ const { operationId, stepIndex, context, payload, delay = 50 } = message;const taskId = `local-${operationId}-${stepIndex}-${Date.now()}`;@@ -60,7 +61,7 @@ export class LocalQueueServiceImpl implements QueueServiceImpl {try {log('Starting local execution for step %d of operation %s', stepIndex, operationId);- await this.executionCallback(operationId, stepIndex, context);+ await this.executionCallback(operationId, stepIndex, context, payload);log('Completed local execution for step %d of operation %s', stepIndex, operationId);} catch (error) {log(diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.tsindex aa351d2c7ce..134f6fe0b17 100644--- a/src/server/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts@@ -488,4 +488,73 @@ describe('lobeAgentRuntime', () => {});expect(mockChat).not.toHaveBeenCalled();});++ describe('callSubAgent', () => {+ it('returns a deferred result and kicks off the sub-agent via the injected runner', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);+ const run = vi+ .fn()+ .mockResolvedValue({ started: true, subOperationId: 'sub-op-1', threadId: 'thread-1' });++ const result = await runtime.callSubAgent(+ { description: 'Research', instruction: 'Find the answer', timeout: 1000 },+ { ...baseContext, subAgent: { run } } as ToolExecutionContext,+ );++ expect(run).toHaveBeenCalledWith({+ description: 'Research',+ instruction: 'Find the answer',+ timeout: 1000,+ });+ expect(result).toMatchObject({+ content: '',+ deferred: true,+ state: { status: 'pending', subOperationId: 'sub-op-1', threadId: 'thread-1' },+ success: true,+ });+ });++ it('returns a non-deferred error when the sub-agent fails to start', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);+ // Child op never started: no completion bridge will fire, so the parent+ // must not park β surface an inline tool error instead.+ const run = vi.fn().mockResolvedValue({ started: false, threadId: '' });++ const result = await runtime.callSubAgent(+ { description: 'Research', instruction: 'Find the answer' },+ { ...baseContext, subAgent: { run } } as ToolExecutionContext,+ );++ expect(result.success).toBe(false);+ expect(result.deferred).toBeUndefined();+ expect(result).toMatchObject({ error: { code: 'SUB_AGENT_START_FAILED' } });+ });++ it('fails (not deferred) when no sub-agent runner is available', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);++ const result = await runtime.callSubAgent(+ { description: 'Research', instruction: 'Find the answer' },+ baseContext,+ );++ expect(result.success).toBe(false);+ expect(result.deferred).toBeUndefined();+ expect(result).toMatchObject({ error: { code: 'SUB_AGENT_UNAVAILABLE' } });+ });++ it('fails when instruction is missing', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);+ const run = vi.fn();++ const result = await runtime.callSubAgent(+ { description: 'Research' } as any,+ { ...baseContext, subAgent: { run } } as ToolExecutionContext,+ );++ expect(result.success).toBe(false);+ expect(result).toMatchObject({ error: { code: 'INVALID_ARGUMENTS' } });+ expect(run).not.toHaveBeenCalled();+ });+ });});diff --git a/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts b/src/server/services/toolExecution/serverRuntimes/lobeAgent.tsindex a8f39cc6783..0837896a0b4 100644--- a/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -1,4 +1,8 @@-import type { VisualFileItem, VisualSourceMessage } from '@lobechat/builtin-tool-lobe-agent';+import type {+ CallSubAgentParams,+ VisualFileItem,+ VisualSourceMessage,+} from '@lobechat/builtin-tool-lobe-agent';import {buildAnalyzeVisualMediaContent,createUrlVisualFileItems,@@ -22,6 +26,7 @@ import { toolsEnv } from '@/envs/tools';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { FileService } from '@/server/services/file';+import type { ToolExecutionContext } from '../types';import { createServerPlanRuntimeService } from './lobeAgentPlan';import type { ServerRuntimeRegistration } from './types';@@ -105,6 +110,56 @@ class LobeAgentExecutionRuntime {clearTodos = (params: any) =>this.planRuntime.clearTodos(params, { messageId: this.messageId, topicId: this.topicId });+ // ==================== Sub-agent (async suspend/resume) ====================++ /**+ * Fork a sub-agent as an independent async operation.+ *+ * Returns a `deferred` result instead of a tool_result: the agent runtime+ * parks the parent op (`waiting_for_async_tool`) until the sub-op finishes,+ * at which point the completion bridge backfills the placeholder tool message+ * and resumes the parent. The placeholder + child-op kickoff are handled by+ * the injected `ctx.subAgent` runner (which owns the parent message anchor).+ */+ callSubAgent = async (+ params: CallSubAgentParams,+ ctx: ToolExecutionContext,+ ): Promise<BuiltinServerRuntimeOutput> => {+ if (!ctx.subAgent) {+ return buildError(+ 'Sub-agent execution is not available in this runtime.',+ 'SUB_AGENT_UNAVAILABLE',+ );+ }++ const { description, instruction, timeout } = params;+ if (!instruction || typeof instruction !== 'string') {+ return buildError('instruction is required.', 'INVALID_ARGUMENTS');+ }++ const { started, threadId, subOperationId } = await ctx.subAgent.run({+ description,+ instruction,+ timeout,+ });++ // The child op failed to start β no completion bridge will ever fire to+ // backfill a placeholder, so we must NOT defer/park here. Return a normal+ // (non-deferred) tool error so the parent's LLM sees the failure and the+ // batch continues instead of hanging in `waiting_for_async_tool`.+ if (!started) {+ return buildError('Sub-agent failed to start.', 'SUB_AGENT_START_FAILED');+ }++ return {+ // No tool_result yet β the bridge fills this in when the sub-op completes.+ content: '',+ deferred: true,+ state: { status: 'pending', subOperationId, threadId },+ success: true,+ };+ };+private queryScopeMessages = (messageModel: MessageModel,sourceMessage: ServerVisualSourceMessage,diff --git a/src/server/services/toolExecution/types.ts b/src/server/services/toolExecution/types.tsindex 01daaccf331..62d9e1fe02d 100644--- a/src/server/services/toolExecution/types.ts+++ b/src/server/services/toolExecution/types.ts@@ -1,6 +1,10 @@import { type LobeToolManifest } from '@lobechat/context-engine';import { type LobeChatDatabase } from '@lobechat/database';-import { type ChatToolPayload, type ClientSecretPayload } from '@lobechat/types';+import {+ type ChatToolPayload,+ type ClientSecretPayload,+ type ExecSubAgentTaskParams,+} from '@lobechat/types';export interface ToolExecutionMemoryEmbeddingRuntime {/** Embedding model id used by the memory search runtime. */@@ -11,6 +15,44 @@ export interface ToolExecutionMemoryEmbeddingRuntime {provider: string;}+export interface ServerSubAgentRunParams {+ /** Target agent id; defaults to the parent agent when omitted. */+ agentId?: string;+ /** Short label shown in the UI (sub-agent thread title). */+ description: string;+ /** Detailed instruction/prompt for the sub-agent run. */+ instruction: string;+ /** Optional per-run timeout in milliseconds. */+ timeout?: number;+}++export interface ServerSubAgentRunResult {+ /**+ * Whether the child op was actually forked. `false` means the child failed to+ * start (e.g. the operation row could not be created/scheduled): no completion+ * bridge will ever fire, so the caller must surface an inline tool error+ * instead of parking the parent β otherwise the parent hangs forever.+ */+ started: boolean;+ /** The spawned child operation id. */+ subOperationId?: string;+ /** The isolation thread holding the sub-agent's full message trace. */+ threadId: string;+}++/**+ * Server-side sub-agent runner injected per tool call by the agent runtime.+ *+ * Unlike the client runner (which blocks until the sub-agent finishes), the+ * server runner only kicks off the child operation asynchronously: it creates+ * the pending placeholder tool message that anchors the isolation thread, forks+ * the child op, and returns immediately. The real result is delivered later by+ * the completion bridge, which backfills the placeholder and resumes the parent.+ */+export interface ServerSubAgentRunner {+ run: (params: ServerSubAgentRunParams) => Promise<ServerSubAgentRunResult>;+}+export interface ToolExecutionContext {/** Target device ID for device proxy tool calls */activeDeviceId?: string;@@ -18,6 +60,12 @@ export interface ToolExecutionContext {agentId?: string;/** Current page document ID for page-scoped conversations */documentId?: string | null;+ /**+ * Spawn a sub-agent as an independent async operation. Injected by the agent+ * runtime (forwarded from `RuntimeExecutorContext.execSubAgentTask`) so the+ * `callSubAgent` server tool can fork a child op without a circular import.+ */+ execSubAgentTask?: (params: ExecSubAgentTaskParams) => Promise<unknown>;/** Per-call execution timeout resolved by the agent runtime. */executionTimeoutMs?: number;/** Current group ID for group chat context */@@ -46,6 +94,13 @@ export interface ToolExecutionContext {serverDB?: LobeChatDatabase;/** Skip low-level result truncation so the AgentRuntime boundary can archive full content first. */skipResultTruncation?: boolean;+ /**+ * Server-side sub-agent runner, injected per tool call by the agent runtime+ * (closes over the current tool payload + parent message). The `callSubAgent`+ * server tool calls `subAgent.run(...)` to fork a child op and returns a+ * `deferred` result; the completion bridge backfills + resumes the parent.+ */+ subAgent?: ServerSubAgentRunner;/** Task ID when executing within the Task system */taskId?: string;/** Current thread ID for thread-scoped conversations */@@ -65,6 +120,12 @@ export interface ToolExecutionContext {export interface ToolExecutionResult {content: string;+ /**+ * When true, the result is delivered out-of-band later (e.g. an async+ * sub-agent). The agent runtime parks the operation instead of writing a+ * tool_result. Mirrors the client-tool pause path.+ */+ deferred?: boolean;error?: any;state?: Record<string, any>;success: boolean;diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.tsindex 53f808a51fd..ea7de067e23 100644--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts@@ -551,10 +551,14 @@ export const createGatewayEventHandler = (action: 'gateway/agent_runtime_end',context,});- } else if (data?.reason === 'interrupted' && hasStreamedContent) {- // MID-stream cancel. The server's+ } else if (+ (data?.reason === 'interrupted' || data?.reason === 'waiting_for_async_tool') &&+ hasStreamedContent+ ) {+ // MID-stream cancel, or a deferred-tool pause+ // (`waiting_for_async_tool`). The server's// `AgentRuntimeCoordinator.resolveUiMessages` omits uiMessages- // for status='interrupted' precisely so we can preserve the+ // for both statuses precisely so we can preserve the// in-memory streamed content here. The executor's partial-// finalize catch writes the real content to DB asynchronously,// but it may not be durable yet β refetching here would race