π€― 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
π fix(agent): deliver sub-agent resume bridge via QStash webhook in queue mode (#15620)
Arvin Xufdb529d598f0
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 2d5ef36bf2c..9058aa21473 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -3,6 +3,7 @@*/import { getModelPropertyWithFallback } from '@lobechat/model-runtime';import type * as ModelBankModule from 'model-bank';+import type { MockInstance } from 'vitest';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -1624,5 +1625,168 @@ describe('AgentRuntimeService', () => {expect(won).toBe(false);expect(casSpy).not.toHaveBeenCalled();});++ it('arms a one-shot verify when the parent has not parked yet and scheduleVerifyOnHold is set', async () => {+ // Child completed before the parent's parking step persisted its state.+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [],+ status: 'running',+ stepCount: 2,+ });++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true },+ );++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ operationId: parentOpId,+ payload: { verifyAsyncToolBarrier: true },+ stepIndex: 2,+ }),+ );+ });++ it('arms a one-shot verify when the barrier is unsatisfied and scheduleVerifyOnHold is set', 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 won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true },+ );++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({ payload: { verifyAsyncToolBarrier: true } }),+ );+ });++ it('does not arm a verify for terminal parent states', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [],+ status: 'done',+ stepCount: 5,+ });++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true },+ );++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });+ });++ describe('completeSubAgentBridge', () => {+ const bridgeParams = {+ operationId: 'child-op-1',+ parentOperationId: 'parent-op-1',+ reason: 'done',+ threadId: 'thread-1',+ toolMessageId: 'tool-msg-1',+ };++ const childState = {+ messages: [+ { content: 'question', role: 'user' },+ { content: 'final answer', role: 'assistant' },+ ],+ modelRuntimeConfig: { model: 'gpt-test' },+ status: 'done',+ usage: { llm: { tokens: { total: 42 } }, tools: { totalCalls: 2 } },+ };++ let updateToolMessage: ReturnType<typeof vi.fn>;+ let resumeSpy: MockInstance<AgentRuntimeService['tryResumeParentFromAsyncTool']>;++ beforeEach(() => {+ updateToolMessage = vi.fn().mockResolvedValue({ success: true });+ (service as any).messageModel.updateToolMessage = updateToolMessage;+ resumeSpy = vi.spyOn(service, 'tryResumeParentFromAsyncTool').mockResolvedValue(true);+ });++ it('backfills the tool message from finalState and resumes with scheduleVerifyOnHold', async () => {+ const won = await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: childState as any,+ });++ expect(won).toBe(true);+ expect(updateToolMessage).toHaveBeenCalledWith('tool-msg-1', {+ content: 'final answer',+ pluginError: undefined,+ pluginState: {+ model: 'gpt-test',+ status: 'completed',+ threadId: 'thread-1',+ totalToolCalls: 2,+ totalTokens: 42,+ },+ });+ expect(resumeSpy).toHaveBeenCalledWith(+ { parentOperationId: 'parent-op-1' },+ { scheduleVerifyOnHold: true },+ );+ });++ it('loads the child state from the coordinator when finalState is not passed (webhook path)', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(childState);++ await service.completeSubAgentBridge(bridgeParams);++ expect(mockCoordinator.loadAgentState).toHaveBeenCalledWith('child-op-1');+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'final answer' }),+ );+ });++ it('writes an error note + pluginError when the child failed', async () => {+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: { ...childState, error: { message: 'boom' } } as any,+ reason: 'error',+ });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({+ content: 'Sub-agent did not complete (error).',+ pluginError: { message: 'boom' },+ pluginState: expect.objectContaining({ status: 'error' }),+ }),+ );+ });++ it('throws when the backfill reports success: false so the webhook path redelivers', async () => {+ // updateToolMessage swallows transaction errors into { success: false } β+ // acking 200 here would strand the parent: the barrier stays unsatisfied+ // and QStash never retries an acknowledged delivery.+ updateToolMessage.mockResolvedValue({ success: false });++ await expect(+ service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any }),+ ).rejects.toThrow(/failed to backfill/);+ expect(resumeSpy).not.toHaveBeenCalled();+ });++ it('propagates backfill infrastructure errors for the same redelivery', async () => {+ updateToolMessage.mockRejectedValue(new Error('db down'));++ await expect(+ service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any }),+ ).rejects.toThrow('db down');+ expect(resumeSpy).not.toHaveBeenCalled();+ });});});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 297e45280a1..d68f0b0184f 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -67,6 +67,7 @@ import {type StartExecutionParams,type StartExecutionResult,type StepCompletionReason,+ type SubAgentBridgeParams,} from './types';if (process.env.VERCEL) {@@ -76,6 +77,25 @@ if (process.env.VERCEL) {const log = debug('lobe-server:agent-runtime-service');+/**+ * Delay before a one-shot `verifyAsyncToolBarrier` re-check fires after a+ * sub-agent completion found the parent not yet resumable. Long enough for+ * the parent's parking step to finish persisting, short enough that a lost+ * resume is recovered promptly.+ */+const ASYNC_TOOL_VERIFY_DELAY_MS = 15_000;++/**+ * Format error for storage in message pluginError metadata.+ * Handles Error objects which don't serialize properly with JSON.stringify.+ */+const formatErrorForMetadata = (error: unknown): Record<string, any> | undefined => {+ if (!error) return undefined;+ if (error instanceof Error) return { message: error.message, name: error.name };+ if (typeof error === 'object' && 'message' in error) return error as Record<string, any>;+ return { message: String(error) };+};+const toAgentSignalSnapshotEvents = (emission: Awaited<ReturnType<typeof emitAgentSignalSourceEvent>> | undefined,) => {@@ -557,9 +577,24 @@ export class AgentRuntimeService {rejectAndContinue,resumeAsyncTool,toolMessageId,+ verifyAsyncToolBarrier,externalRetryCount = 0,} = params;+ // Watchdog re-check for a parked async-tool wait: re-run the barrier + CAS+ // without claiming the step lock or executing anything. Idempotent β the+ // CAS guarantees at most one real resume regardless of how many checks run.+ if (verifyAsyncToolBarrier) {+ log('[%s][%d] Running async-tool barrier verify', operationId, stepIndex);+ const resumed = await this.tryResumeParentFromAsyncTool({ parentOperationId: operationId });+ return {+ nextStepScheduled: resumed,+ state: {},+ stepResult: null,+ success: true,+ };+ }+// ===== Distributed lock: prevent duplicate execution from QStash retries =====const claimed = await this.coordinator.tryClaimStep(operationId, stepIndex, 35);if (!claimed) {@@ -1047,6 +1082,26 @@ export class AgentRuntimeService {// Dispatch completion hooksawait this.completionLifecycle.dispatchHooks(operationId, stepResult.newState, reason);+ // Park-time self-check: sub-agents are dispatched mid-step, so a+ // fast child can complete BEFORE this op's parked state/row were+ // persisted β its resume attempt then no-ops against the status+ // guard and nothing retries. Now that both the Redis state and the+ // `agent_operations` row (via dispatchHooks β persistCompletion)+ // say `waiting_for_async_tool`, re-run the barrier once to recover+ // any resume that raced the park.+ if (stepResult.newState.status === 'waiting_for_async_tool') {+ try {+ await this.tryResumeParentFromAsyncTool({ parentOperationId: operationId });+ } catch (selfCheckError) {+ log(+ '[%s][%d] Park-time async-tool self-check failed (non-fatal): %O',+ operationId,+ stepIndex,+ selfCheckError,+ );+ }+ }+// Finalize tracing snapshot. The error catch below uses the same// recorder so propagated failures still write the canonical S3// snapshot instead of orphaning the partial ().@@ -1541,12 +1596,33 @@ export class AgentRuntimeService {* the LLM with the refreshed tool results.** Returns true only for the CAS winner that scheduled the resume.+ *+ * `options.scheduleVerifyOnHold` arms a one-shot delayed re-check+ * (`verifyAsyncToolBarrier`) when the parent is found not yet resumable.+ * Sub-agent completions set it to cover the child finishing before the+ * parent's parked state is persisted, and transient failures around the+ * last completion (a sibling dying between backfill and resume, a DB+ * hiccup during the barrier read). Pure concurrency needs no cover: each+ * completion checks the barrier only after committing its own backfill, so+ * the last committer always sees every earlier one. The re-check itself+ * never re-arms, so retries stay bounded.*/- async tryResumeParentFromAsyncTool(params: { parentOperationId: string }): Promise<boolean> {+ async tryResumeParentFromAsyncTool(+ params: { parentOperationId: string },+ options?: { scheduleVerifyOnHold?: boolean },+ ): Promise<boolean> {const { parentOperationId } = params;const state = await this.coordinator.loadAgentState(parentOperationId);- if (!state || state.status !== 'waiting_for_async_tool') return false;+ if (!state) return false;++ if (state.status !== 'waiting_for_async_tool') {+ // Not parked (yet). Either the op already resumed/finished β nothing to+ // do β or the child outran the parent's parking step; the delayed verify+ // re-checks once the park has had time to land.+ await this.maybeScheduleAsyncToolVerify(parentOperationId, state, options);+ return false;+ }const pending = (state.pendingToolsCalling ?? []) as ChatToolPayload[];if (pending.length === 0) return false;@@ -1555,6 +1631,7 @@ export class AgentRuntimeService {const allFulfilled = await this.allPendingToolsFulfilled(pending);if (!allFulfilled) {log('[%s] async-tool barrier not yet satisfied, holding', parentOperationId);+ await this.maybeScheduleAsyncToolVerify(parentOperationId, state, options);return false;}@@ -1586,6 +1663,121 @@ export class AgentRuntimeService {return true;}+ /**+ * Arm a one-shot delayed `verifyAsyncToolBarrier` re-check for a parent op+ * whose resume attempt found it not yet resumable. Skipped for terminal+ * states (nothing left to resume) and when the caller didn't opt in β the+ * verify execution itself never re-arms, keeping retries bounded to one+ * per completion event.+ */+ private async maybeScheduleAsyncToolVerify(+ parentOperationId: string,+ state: AgentState,+ options?: { scheduleVerifyOnHold?: boolean },+ ): Promise<void> {+ if (!options?.scheduleVerifyOnHold || !this.queueService) return;++ const status = state.status as string;+ if (status === 'done' || status === 'error' || status === 'interrupted') return;++ log(+ '[%s] scheduling async-tool barrier verify in %dms (status: %s)',+ parentOperationId,+ ASYNC_TOOL_VERIFY_DELAY_MS,+ status,+ );++ try {+ await this.queueService.scheduleMessage({+ context: undefined,+ delay: ASYNC_TOOL_VERIFY_DELAY_MS,+ endpoint: `${this.baseURL}/run`,+ operationId: parentOperationId,+ payload: { verifyAsyncToolBarrier: true },+ priority: 'high',+ stepIndex: state.stepCount,+ });+ } catch (error) {+ log(+ '[%s] failed to schedule async-tool barrier verify (non-fatal): %O',+ parentOperationId,+ error,+ );+ }+ }++ /**+ * Sub-agent completion bridge for the server `callSubAgent` deferred-tool+ * path. Runs when a child sub-agent op reaches a terminal state β invoked+ * in-process by the child's `onComplete` hook handler (local mode) or via+ * the QStash-delivered `/webhooks/subagent-callback` endpoint (queue mode,+ * where in-memory handler hooks don't survive cross-process steps).+ *+ * 1. Backfill 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. Resume the parked parent: barrier-check + CAS via+ * `tryResumeParentFromAsyncTool`, arming the delayed verify when the+ * parent isn't resumable yet.+ *+ * THROWS on infrastructure failure of either half (state load, backfill,+ * resume) so the queue-mode callback returns non-2xx and QStash redelivers+ * the whole bridge β the delayed verify alone cannot recover a failed+ * backfill, it only re-reads the barrier. Redelivery is safe: the backfill+ * rewrites the same content and the resume is CAS-guarded.+ *+ * Returns true when this call won the resume CAS.+ */+ async completeSubAgentBridge(params: SubAgentBridgeParams): Promise<boolean> {+ const { operationId, parentOperationId, reason, threadId, toolMessageId } = params;+ const failed = reason === 'error' || reason === 'interrupted';++ // Infra errors propagate; a null state (expired) degrades to a stub note.+ const finalState =+ params.finalState ?? (await this.coordinator.loadAgentState(operationId)) ?? undefined;++ log(+ '[%s] sub-agent bridge β parent %s (reason: %s, state: %s)',+ operationId,+ parentOperationId,+ reason,+ finalState ? 'loaded' : 'missing',+ );++ // 1. Backfill the placeholder tool message with the result.+ // `updateToolMessage` swallows transaction errors into `success: false`,+ // so the flag must be checked β an unfulfilled message would hold the+ // parent's barrier forever while the callback acked with 200.+ const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];+ const lastAssistant = [...messages]+ .reverse()+ .find((m: { role?: string }) => m?.role === 'assistant');+ const content = failed+ ? `Sub-agent did not complete (${reason}).`+ : (lastAssistant?.content as string | undefined) ||+ 'Sub-agent completed without a textual answer.';++ const backfill = 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: finalState?.usage?.llm?.tokens?.total,+ },+ });+ if (!backfill.success) {+ throw new Error(+ `Sub-agent bridge: failed to backfill tool message ${toolMessageId} for parent ${parentOperationId}`,+ );+ }++ // 2. Barrier + CAS + resume the parent op (infra errors propagate too)+ return this.tryResumeParentFromAsyncTool({ parentOperationId }, { scheduleVerifyOnHold: 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 adiff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.tsindex 5d2e8a3ee32..413fe355dd2 100644--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts@@ -22,7 +22,7 @@ export async function deliverWebhook(webhook: AgentHookWebhook,payload: Record<string, unknown>,): Promise<void> {- const { url, delivery = 'fetch' } = webhook;+ const { url, delivery = 'fetch', fallback = 'fetch' } = webhook;// Resolve URL: relative paths joined with INTERNAL_APP_URL or APP_URLconst resolvedUrl = url.startsWith('http')@@ -34,6 +34,9 @@ export async function deliverWebhook(const { Client } = await import('@upstash/qstash');const qstashToken = process.env.QSTASH_TOKEN;if (!qstashToken) {+ if (fallback === 'none') {+ throw new Error(`QSTASH_TOKEN not available for qstash-only webhook: ${url}`);+ }log('QStash token not available, falling back to fetch delivery');await fetchDeliver(resolvedUrl, payload);return;@@ -50,6 +53,11 @@ export async function deliverWebhook(});log('Webhook delivered via QStash: %s', url);} catch (error) {+ // An unsigned fetch can never authenticate against a QStash-signed+ // endpoint β falling back would just be a silently-dropped 401. Let+ // the failure surface to the dispatcher instead.+ if (fallback === 'none') throw error;+log('QStash delivery failed, falling back to fetch: %O', error);await fetchDeliver(resolvedUrl, payload);}@@ -157,13 +165,23 @@ export class HookDispatcher {...hook.webhook.body,});} catch (error) {- log(- '[%s][%s] Webhook delivery error (non-fatal): %s %O',- operationId,- type,- hook.id,- error,- );+ if (hook.webhook.fallback === 'none') {+ // No-fallback webhooks carry control flow (e.g. the sub-agent+ // resume bridge) β losing one strands its consumer, so surface+ // the failure in production logs, not just the debug namespace.+ console.error(+ `[HookDispatcher][${operationId}][${type}] Webhook delivery failed with no fallback: ${hook.id} β ${hook.webhook.url}`,+ error,+ );+ } else {+ log(+ '[%s][%s] Webhook delivery error (non-fatal): %s %O',+ operationId,+ type,+ hook.id,+ error,+ );+ }}}}diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.tsindex e92f8fbf5b8..b922253717d 100644--- a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { HookDispatcher } from '../HookDispatcher';+import { deliverWebhook, HookDispatcher } from '../HookDispatcher';import type { AgentHook, AgentHookEvent } from '../types';// Mock isQueueAgentRuntimeEnabled to control local vs production mode@@ -8,6 +8,16 @@ vi.mock('@/server/services/queue/impls', () => ({isQueueAgentRuntimeEnabled: vi.fn(() => false), // Default: local mode}));+const mockPublishJSON = vi.hoisted(() => vi.fn());++// Plain class (not vi.fn) so the file-level `vi.restoreAllMocks()` can't wipe+// the implementation between tests.+vi.mock('@upstash/qstash', () => ({+ Client: class {+ publishJSON = mockPublishJSON;+ },+}));+const { isQueueAgentRuntimeEnabled } = await import('@/server/services/queue/impls');describe('HookDispatcher', () => {@@ -259,6 +269,89 @@ describe('HookDispatcher', () => {});});+ describe('deliverWebhook qstash fallback', () => {+ const originalToken = process.env.QSTASH_TOKEN;++ beforeEach(() => {+ global.fetch = vi.fn().mockResolvedValue({ status: 200 });+ mockPublishJSON.mockReset();+ delete process.env.QSTASH_TOKEN;+ });++ afterEach(() => {+ if (originalToken === undefined) delete process.env.QSTASH_TOKEN;+ else process.env.QSTASH_TOKEN = originalToken;+ vi.restoreAllMocks();+ });++ it('falls back to plain fetch by default when the QStash token is missing', async () => {+ await deliverWebhook({ delivery: 'qstash', url: 'https://example.com/hook' }, { a: 1 });++ expect(global.fetch).toHaveBeenCalled();+ });++ it("throws instead of unsigned-fetching when fallback is 'none' and the token is missing", async () => {+ await expect(+ deliverWebhook(+ { delivery: 'qstash', fallback: 'none', url: 'https://example.com/hook' },+ { a: 1 },+ ),+ ).rejects.toThrow(/QSTASH_TOKEN not available/);++ expect(global.fetch).not.toHaveBeenCalled();+ });++ it("throws instead of unsigned-fetching when fallback is 'none' and the publish fails", async () => {+ process.env.QSTASH_TOKEN = 'test-token';+ mockPublishJSON.mockRejectedValue(new Error('qstash down'));++ await expect(+ deliverWebhook(+ { delivery: 'qstash', fallback: 'none', url: 'https://example.com/hook' },+ { a: 1 },+ ),+ ).rejects.toThrow('qstash down');++ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('dispatch surfaces a no-fallback delivery failure without breaking other hooks', async () => {+ vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ dispatcher.register(operationId, [+ {+ handler: vi.fn(),+ id: 'critical-hook',+ type: 'onComplete',+ webhook: { delivery: 'qstash', fallback: 'none', url: 'https://example.com/critical' },+ },+ {+ handler: vi.fn(),+ id: 'normal-hook',+ type: 'onComplete',+ webhook: { url: 'https://example.com/normal' },+ },+ ]);++ const serialized = dispatcher.getSerializedHooks(operationId);+ await expect(+ dispatcher.dispatch(operationId, 'onComplete', makeEvent(), serialized),+ ).resolves.toBeUndefined();++ // The failure is escalated to production logs, and the sibling webhook+ // still gets delivered.+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('critical-hook'),+ expect.any(Error),+ );+ expect(global.fetch).toHaveBeenCalledWith(+ 'https://example.com/normal',+ expect.objectContaining({ method: 'POST' }),+ );+ });+ });+describe('getSerializedHooks', () => {it('should return only hooks with webhook config', () => {dispatcher.register(operationId, [diff --git a/apps/server/src/services/agentRuntime/hooks/types.ts b/apps/server/src/services/agentRuntime/hooks/types.tsindex 7e620c82fb5..3e57eb43eac 100644--- a/apps/server/src/services/agentRuntime/hooks/types.ts+++ b/apps/server/src/services/agentRuntime/hooks/types.ts@@ -41,6 +41,15 @@ export interface AgentHookWebhook {/** Event fields to include in the webhook payload. Defaults to all serializable event fields. */eventFields?: (keyof AgentHookEvent)[];+ /**+ * Behavior when QStash delivery fails (publish error or missing+ * QSTASH_TOKEN). 'fetch' (default, legacy) retries as a plain unsigned+ * POST; 'none' throws instead. Use 'none' for endpoints behind QStash+ * signature auth β an unsigned fallback can never authenticate there, so+ * it only masks the delivery failure as a silently-dropped 401.+ */+ fallback?: 'fetch' | 'none';+/** Webhook endpoint URL (relative or absolute) */url: string;}diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 67c98b00470..32295813a5c 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -140,6 +140,15 @@ export interface AgentExecutionParams {stepIndex: number;/** ID of the pending tool message targeted by the intervention. */toolMessageId?: string;+ /**+ * Watchdog re-check for a parked `waiting_for_async_tool` op: re-runs the+ * resume barrier + CAS without claiming the step lock or executing a step.+ * A no-op when the op already resumed or the barrier is still unsatisfied.+ * Scheduled one-shot by `tryResumeParentFromAsyncTool` when a sub-agent+ * completion found the parent not yet resumable (covers the+ * child-finishes-before-parent-parks race and transient barrier failures).+ */+ verifyAsyncToolBarrier?: boolean;}export interface AgentExecutionResult {@@ -154,6 +163,22 @@ export interface AgentExecutionResult {success: boolean;}+/**+ * Params for the sub-agent completion bridge β see+ * `AgentRuntimeService.completeSubAgentBridge`.+ */+export interface SubAgentBridgeParams {+ /** Child op's final state β passed in local mode; loaded from the coordinator otherwise. */+ finalState?: AgentState;+ /** Child (sub-agent) operation ID. */+ operationId: string;+ parentOperationId: string;+ reason: string;+ threadId: string;+ /** The parent's placeholder `role: 'tool'` message to backfill. */+ toolMessageId: string;+}+export interface OperationCreationParams {activeDeviceId?: string;agentConfig?: any;diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 0fc2ac0e8b8..fb8cbf53c19 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -75,6 +75,7 @@ import type {AgentExecutionParams,AgentExecutionResult,AgentRuntimeServiceOptions,+ SubAgentBridgeParams,} from '@/server/services/agentRuntime';import { AgentRuntimeService } from '@/server/services/agentRuntime';import { getAbortError, isAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';@@ -414,6 +415,19 @@ export class AiAgentService {return this.agentRuntimeService.executeStep(params);}+ /**+ * Run the sub-agent completion bridge against this service's runtime.+ *+ * Same rationale as `executeStep`: the QStash `subagent-callback` webhook+ * drives the bridge through here so the runtime's models stay+ * workspace-scoped β a bare AgentRuntimeService would be personal-scoped+ * and the tool-message backfill / resume barrier could miss+ * workspace-scoped rows.+ */+ completeSubAgentBridge(params: SubAgentBridgeParams): Promise<boolean> {+ return this.agentRuntimeService.completeSubAgentBridge(params);+ }+/*** Execute agent with just a prompt*@@ -3164,14 +3178,18 @@ 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.+ * Fires on the sub-op's completion (success or failure) and delegates to+ * `AgentRuntimeService.completeSubAgentBridge`: backfill the parent's+ * placeholder tool message, then barrier-check + CAS-resume the parked+ * parent op.+ *+ * Transport adapts to the runtime mode like every other lifecycle hook:+ * - local mode: the `handler` runs in-process with the child's finalState.+ * - queue mode: in-memory handlers don't survive cross-process steps, so+ * the serialized `webhook` config is delivered via QStash to+ * `/api/agent/webhooks/subagent-callback`, which re-enters the same+ * bridge method. `delivery: 'qstash'` is required β a plain fetch would+ * be rejected by the endpoint's QStash signature auth.*/private createSubAgentBridgeHook(parentOperationId: string,@@ -3180,45 +3198,18 @@ export class AiAgentService {): 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 resulttry {- 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',+ await this.agentRuntimeService.completeSubAgentBridge({+ finalState: event.finalState,+ operationId: event.operationId,+ parentOperationId,+ reason: event.reason ?? 'done',+ threadId,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',+ 'Sub-agent bridge: failed to complete bridge for parent %s: %O',parentOperationId,error,);@@ -3226,6 +3217,21 @@ export class AiAgentService {},id: 'sub-agent-bridge',type: 'onComplete' as const,+ webhook: {+ body: { parentOperationId, threadId, toolMessageId },+ delivery: 'qstash' as const,+ // Keep the payload lean: the endpoint reloads the child's final state+ // from the coordinator, so everything beyond these ids is dead weight.+ // The default (all event fields) would ship the child's entire final+ // answer (`lastAssistantContent`) β and any tool-produced attachments+ // the shared lifecycle event extractor inlines β through QStash.+ eventFields: ['operationId', 'reason', 'status'],+ // The endpoint sits behind QStash signature auth, so the unsigned+ // fetch fallback could never authenticate β it would only mask a+ // publish failure as a silently-dropped 401, stranding the parent.+ fallback: 'none' as const,+ url: '/api/agent/webhooks/subagent-callback',+ },};}diff --git a/src/server/agent-hono/handlers/__tests__/subAgentCallback.test.ts b/src/server/agent-hono/handlers/__tests__/subAgentCallback.test.tsnew file mode 100644index 00000000000..f072413afd8--- /dev/null+++ b/src/server/agent-hono/handlers/__tests__/subAgentCallback.test.ts@@ -0,0 +1,144 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { subAgentCallback } from '../subAgentCallback';++const mockCompleteSubAgentBridge = vi.fn();+const mockGetOperationMetadata = vi.fn();+const mockAiAgentService = vi.fn();++vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation((...args: any[]) => {+ mockAiAgentService(...args);+ return { completeSubAgentBridge: mockCompleteSubAgentBridge };+ }),+}));++vi.mock('@/server/modules/AgentRuntime', () => ({+ AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({+ getOperationMetadata: mockGetOperationMetadata,+ })),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn().mockResolvedValue({} as any),+}));++function buildContext(opts: { body?: unknown; jsonThrows?: boolean }) {+ const captures: Array<{ body: any; status: number }> = [];+ const ctx = {+ json: (b: any, status = 200) => {+ captures.push({ body: b, status });+ return Response.json(b, { status });+ },+ req: {+ json: opts.jsonThrows+ ? async () => {+ throw new Error('bad json');+ }+ : async () => opts.body,+ },+ } as any;+ return { ctx, getCaptures: () => captures };+}++const validBody = {+ operationId: 'op-child-1',+ parentOperationId: 'op-parent-1',+ reason: 'done',+ threadId: 'thread-1',+ toolMessageId: 'msg-tool-1',+};++describe('subAgentCallback handler', () => {+ beforeEach(() => {+ mockCompleteSubAgentBridge.mockReset();+ mockGetOperationMetadata.mockReset();+ mockAiAgentService.mockReset();+ mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1', workspaceId: 'ws-1' });+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it('returns 400 when JSON parsing throws', async () => {+ const { ctx } = buildContext({ jsonThrows: true });+ const res = await subAgentCallback(ctx);+ expect(res.status).toBe(400);+ expect(mockCompleteSubAgentBridge).not.toHaveBeenCalled();+ });++ it.each([+ ['operationId', { ...validBody, operationId: undefined }],+ ['parentOperationId', { ...validBody, parentOperationId: undefined }],+ ['toolMessageId', { ...validBody, toolMessageId: undefined }],+ ])('returns 400 when required field %s is missing', async (_field, body) => {+ const { ctx, getCaptures } = buildContext({ body });+ const res = await subAgentCallback(ctx);+ expect(res.status).toBe(400);+ expect(getCaptures()[0].body.error).toMatch(/Missing required fields/);+ expect(mockCompleteSubAgentBridge).not.toHaveBeenCalled();+ });++ it('returns 401 when the child operation has no userId', async () => {+ mockGetOperationMetadata.mockResolvedValue(undefined);+ const { ctx } = buildContext({ body: validBody });++ const res = await subAgentCallback(ctx);++ expect(res.status).toBe(401);+ expect(mockCompleteSubAgentBridge).not.toHaveBeenCalled();+ });++ it('runs the bridge and returns 200 on happy path', async () => {+ mockCompleteSubAgentBridge.mockResolvedValue(true);+ const { ctx, getCaptures } = buildContext({ body: validBody });++ const res = await subAgentCallback(ctx);++ expect(res.status).toBe(200);+ expect(getCaptures()[0].body).toEqual({+ operationId: 'op-child-1',+ parentOperationId: 'op-parent-1',+ resumed: true,+ success: true,+ });+ expect(mockCompleteSubAgentBridge).toHaveBeenCalledWith({+ operationId: 'op-child-1',+ parentOperationId: 'op-parent-1',+ reason: 'done',+ threadId: 'thread-1',+ toolMessageId: 'msg-tool-1',+ });+ // Workspace-scoped like the /run step worker β a personal-scoped runtime+ // would miss workspace rows in the backfill / barrier queries.+ expect(mockAiAgentService).toHaveBeenCalledWith(expect.anything(), 'user-1', {+ workspaceId: 'ws-1',+ });+ });++ it('defaults reason to done and threadId to empty string when absent', async () => {+ mockCompleteSubAgentBridge.mockResolvedValue(false);+ const { ctx } = buildContext({+ body: { ...validBody, reason: undefined, threadId: undefined },+ });++ const res = await subAgentCallback(ctx);++ expect(res.status).toBe(200);+ expect(mockCompleteSubAgentBridge).toHaveBeenCalledWith(+ expect.objectContaining({ reason: 'done', threadId: '' }),+ );+ });++ it('returns 500 with the error message when the bridge throws (QStash redelivers)', async () => {+ mockCompleteSubAgentBridge.mockRejectedValue(new Error('redis down'));+ const { ctx, getCaptures } = buildContext({ body: validBody });++ const res = await subAgentCallback(ctx);++ expect(res.status).toBe(500);+ expect(getCaptures()[0].body).toEqual({ error: 'redis down' });+ });+});diff --git a/src/server/agent-hono/handlers/runStep.ts b/src/server/agent-hono/handlers/runStep.tsindex b771ed2b94f..a4797cde5f6 100644--- a/src/server/agent-hono/handlers/runStep.ts+++ b/src/server/agent-hono/handlers/runStep.ts@@ -41,6 +41,7 @@ export async function runStep(c: Context): Promise<Response> {rejectAndContinue,resumeAsyncTool,toolMessageId,+ verifyAsyncToolBarrier,} = { ...body, ...body.payload };if (!operationId) {@@ -82,6 +83,7 @@ export async function runStep(c: Context): Promise<Response> {resumeAsyncTool,stepIndex,toolMessageId,+ verifyAsyncToolBarrier,});// Step is currently being executed by another instance β tell QStash to retry laterdiff --git a/src/server/agent-hono/handlers/subAgentCallback.ts b/src/server/agent-hono/handlers/subAgentCallback.tsnew file mode 100644index 00000000000..638c74503eb--- /dev/null+++ b/src/server/agent-hono/handlers/subAgentCallback.ts@@ -0,0 +1,84 @@+import debug from 'debug';+import type { Context } from 'hono';++import { getServerDB } from '@/database/core/db-adaptor';+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';+import { AiAgentService } from '@/server/services/aiAgent';++const log = debug('lobe-server:agent:subagent-callback');++/**+ * Sub-agent completion bridge webhook (queue mode).+ *+ * When a server sub-agent op β spawned by a parent parked on `callSubAgent` β+ * reaches a terminal state, its `onComplete` hook is delivered here via QStash+ * (in-memory handler hooks don't survive queue mode's cross-process steps).+ * Backfills the parent's placeholder tool message and barrier-resumes the+ * parked parent op via `completeSubAgentBridge`.+ *+ * Body: `{ operationId, reason, parentOperationId, threadId, toolMessageId }`+ * β event fields from the hook dispatch plus the bridge params from+ * `webhook.body`.+ *+ * Auth: `qstashAuth` on the route β QStash signature required.+ */+export async function subAgentCallback(c: Context): Promise<Response> {+ let body: any;+ try {+ body = await c.req.json();+ } catch {+ return c.json({ error: 'Invalid JSON body' }, 400);+ }++ const { operationId, parentOperationId, reason, threadId, toolMessageId } = body;++ log(+ 'subagent-callback: operationId=%s, parentOperationId=%s, reason=%s, toolMessageId=%s',+ operationId,+ parentOperationId,+ reason,+ toolMessageId,+ );++ if (!operationId || !parentOperationId || !toolMessageId) {+ return c.json(+ { error: 'Missing required fields: operationId, parentOperationId, toolMessageId' },+ 400,+ );+ }++ try {+ // Resolve userId from the child operation's metadata β same trust chain as+ // /run: the body is QStash-signature-verified, the operation must exist.+ const coordinator = new AgentRuntimeCoordinator();+ const metadata = await coordinator.getOperationMetadata(operationId);++ if (!metadata?.userId) {+ log('subagent-callback: invalid operation or no userId found for %s', operationId);+ return c.json({ error: 'Invalid operation or unauthorized' }, 401);+ }++ const serverDB = await getServerDB();+ // Bridge through AiAgentService (like the /run step worker) so the+ // runtime's models stay workspace-scoped β a bare AgentRuntimeService+ // would be personal-scoped and the tool-message backfill / resume+ // barrier could miss workspace-scoped rows.+ const aiAgentService = new AiAgentService(serverDB, metadata.userId, {+ workspaceId: metadata.workspaceId,+ });++ const resumed = await aiAgentService.completeSubAgentBridge({+ operationId,+ parentOperationId,+ reason: reason ?? 'done',+ threadId: threadId ?? '',+ toolMessageId,+ });++ return c.json({ operationId, parentOperationId, resumed, success: true });+ } catch (error) {+ console.error('subagent-callback error:', error);+ // Non-2xx β QStash redelivers, covering transient DB/Redis failures.+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);+ }+}diff --git a/src/server/agent-hono/index.ts b/src/server/agent-hono/index.tsindex aefcb8f793a..421f7628c1b 100644--- a/src/server/agent-hono/index.ts+++ b/src/server/agent-hono/index.ts@@ -11,6 +11,7 @@ import { messengerOAuthCallback } from './handlers/messengerOAuthCallback';import { messengerWebhook } from './handlers/messengerWebhook';import { platformWebhook } from './handlers/platformWebhook';import { runStep, runStepHealth } from './handlers/runStep';+import { subAgentCallback } from './handlers/subAgentCallback';import { toolResult } from './handlers/toolResult';import { bearerSecretAuth } from './middlewares/bearerSecretAuth';import { qstashAuth } from './middlewares/qstashAuth';@@ -68,6 +69,9 @@ app.post('/gateway/callback', gatewayCallback);// POST /api/agent/webhooks/bot-callback β agent step/completion webhooks (QStash)app.post('/webhooks/bot-callback', qstashAuth(), botCallback);+// POST /api/agent/webhooks/subagent-callback β sub-agent completion bridge (QStash)+app.post('/webhooks/subagent-callback', qstashAuth(), subAgentCallback);+// POST /api/agent/webhooks/:platform[/:appId] β Chat SDK bot platform webhooksapp.post('/webhooks/:platform/:appId?', platformWebhook);