π€― 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-runtime): strip callSubAgent in server sub-agent runs & resume parent on watchdog abandon (#16345)
Arvin Xu4ac616e4bf84
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.tsindex b7b5c3526f3..a4b0ed626c6 100644--- a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts@@ -2,7 +2,7 @@import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';-import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';+import { LobeAgentApiName, LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { MemoryManifest } from '@lobechat/builtin-tool-memory';import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';@@ -287,6 +287,57 @@ describe('createServerAgentToolsEngine', () => {// lobe-agent is in alwaysOnToolIds, so its core capabilities are on for every agent-mode turn.expect(result.enabledToolIds).toContain(LobeAgentManifest.identifier);++ // Without a manifest context, the full static manifest is used β callSubAgent stays.+ const lobeAgent = result.enabledManifests.find(+ (m) => m.identifier === LobeAgentManifest.identifier,+ );+ expect(lobeAgent?.api.map((a) => a.name)).toContain(LobeAgentApiName.callSubAgent);+ });++ it('hides lobe-agent callSubAgent when manifestContext.isSubAgent is true', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: [] },+ manifestContext: { isSubAgent: true },+ model: 'deepseek-chat',+ provider: 'deepseek',+ });++ const result = engine.generateToolsDetailed({+ model: 'deepseek-chat',+ provider: 'deepseek',+ toolIds: [],+ });++ // lobe-agent's other capabilities (plan / todo / visual-media) stay on...+ expect(result.enabledToolIds).toContain(LobeAgentManifest.identifier);+ const lobeAgent = result.enabledManifests.find(+ (m) => m.identifier === LobeAgentManifest.identifier,+ );+ // ...but callSubAgent is stripped so a nested sub-agent cannot recurse.+ expect(lobeAgent?.api.map((a) => a.name)).not.toContain(LobeAgentApiName.callSubAgent);+ });++ it('hides lobe-agent callSubAgent inside a group run (scope=group)', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: [] },+ manifestContext: { scope: 'group' },+ model: 'deepseek-chat',+ provider: 'deepseek',+ });++ const result = engine.generateToolsDetailed({+ model: 'deepseek-chat',+ provider: 'deepseek',+ toolIds: [],+ });++ const lobeAgent = result.enabledManifests.find(+ (m) => m.identifier === LobeAgentManifest.identifier,+ );+ expect(lobeAgent?.api.map((a) => a.name)).not.toContain(LobeAgentApiName.callSubAgent);});it('should enable KnowledgeBase when hasEnabledKnowledgeBases is true', () => {diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.tsindex 98e4718b013..54efe2bc793 100644--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts@@ -25,7 +25,11 @@ import {} from '@lobechat/builtin-tools';import { createEnableChecker, type LobeToolManifest } from '@lobechat/context-engine';import { ToolsEngine } from '@lobechat/context-engine';-import { type RuntimeEnvMode, type RuntimePlatform } from '@lobechat/types';+import {+ type BuiltinToolManifest,+ type RuntimeEnvMode,+ type RuntimePlatform,+} from '@lobechat/types';import debug from 'debug';import {@@ -72,6 +76,7 @@ export const createServerToolsEngine = (builtinTools: builtinToolsOverride = builtinTools,defaultToolIds,excludeIdentifiers,+ manifestContext,} = config;// Get plugin manifests from installed plugins (from database)@@ -85,7 +90,21 @@ export const createServerToolsEngine = (// and . The enableChecker rules below are defense-in-depth// because `allowExplicitActivation` lets activator-driven activation// bypass them.- const builtinManifests = builtinToolsOverride.map((tool) => tool.manifest as LobeToolManifest);+ //+ // When a manifest context is supplied (agent runtime path), context-aware+ // tools resolve their manifest for it β trimming APIs (e.g. lobe-agent hides+ // callSubAgent inside a sub-agent / group, both list AND systemRole) or opting+ // out entirely via `null`. This MUST mirror the frontend `createToolsEngine`:+ // a sub-agent run server-side that skipped this would still be handed+ // `callSubAgent`, letting the model recurse into nested sub-agents that the+ // runtime then rejects β a dead loop that ends in the inactivity watchdog.+ const builtinManifests = builtinToolsOverride+ .map((tool) =>+ manifestContext && tool.resolveManifest+ ? tool.resolveManifest(manifestContext)+ : tool.manifest,+ )+ .filter((m): m is BuiltinToolManifest => !!m) as LobeToolManifest[];// Combine all manifests, then drop anything whose identifier the caller// has explicitly forbidden for this turn. The post-merge filter closes@@ -138,6 +157,7 @@ export const createServerAgentToolsEngine = (hasEnabledKnowledgeBases = false,isBotConversation = false,isGroupSupervisor = false,+ manifestContext,model,provider,} = params;@@ -280,6 +300,9 @@ export const createServerAgentToolsEngine = (// them from the combined `manifestSchemas` so the activator cannot// resolve them regardless of which manifest source declared them.excludeIdentifiers: canUseDevice ? undefined : DEVICE_TOOL_IDENTIFIERS,+ // Conversation context for context-aware builtin manifests (scope /+ // isSubAgent), e.g. hiding lobe-agent's callSubAgent in sub-agent / group runs.+ manifestContext,enableChecker: createEnableChecker({// Allow lobe-activator to dynamically enable tools at runtime (e.g., lobe-creds, lobe-cron).// Only in agent mode; chat/custom modes can't let the activator bypass their fixed set.diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/types.tsindex cb4f59bae88..e3d7052a545 100644--- a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts@@ -1,5 +1,10 @@import { type LobeToolManifest, type PluginEnableChecker } from '@lobechat/context-engine';-import { type LobeAgentAgencyConfig, type LobeBuiltinTool, type LobeTool } from '@lobechat/types';+import {+ type BuiltinToolResolveContext,+ type LobeAgentAgencyConfig,+ type LobeBuiltinTool,+ type LobeTool,+} from '@lobechat/types';import type { ExecutionPlan } from '@/helpers/executionTarget';@@ -44,6 +49,14 @@ export interface ServerAgentToolsEngineConfig {* This is the final post-merge wall referenced in .*/excludeIdentifiers?: ReadonlySet<string>;+ /**+ * Runtime context for context-aware builtin manifests. When provided, each+ * builtin tool with a `resolveManifest` produces its manifest for this context+ * (e.g. lobe-agent drops `callSubAgent` + its systemRole section inside a+ * sub-agent / group run). Omit for context-free callers β they get the full+ * static manifests. Mirrors the frontend `ToolsEngineConfig.manifestContext`.+ */+ manifestContext?: BuiltinToolResolveContext;}/**@@ -113,6 +126,13 @@ export interface ServerCreateAgentToolsEngineParams {* When true the engine auto-enables the group-management + agent-builder tools.*/isGroupSupervisor?: boolean;+ /**+ * Conversation context for context-aware builtin manifests (scope,+ * isSubAgent). Forwarded to `createServerToolsEngine` so tools like+ * lobe-agent can self-trim β hiding `callSubAgent` (tool + systemRole)+ * inside a sub-agent / group run.+ */+ manifestContext?: BuiltinToolResolveContext;/** Model name for function calling compatibility check */model: string;/** Provider name for function calling compatibility check */diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex c4ae51f599d..326ef0209f7 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -3,7 +3,9 @@ import type { ChatMessageError } from '@lobechat/types';import { AgentRuntimeErrorType } from '@lobechat/types';import debug from 'debug';+import { AgentOperationModel } from '@/database/models/agentOperation';import { MessageModel } from '@/database/models/message';+import { ThreadModel } from '@/database/models/thread';import type { LobeChatDatabase } from '@/database/type';// Direct file import (not the barrel) to avoid pulling in RuntimeExecutors and// its workspace-package transitive deps in the unit-test environment.@@ -19,6 +21,21 @@ interface AbandonOperationOptions {snapshotStore?: ISnapshotStore | null;}+/**+ * Linkage for resuming the parent of an abandoned sub-agent. Surfaced so the+ * caller can run the `completeSubAgentBridge` β the watchdog-abandon path+ * otherwise skips the child's onComplete bridge and strands the parent in+ * `waiting_for_async_tool` forever (the orphaned-parent bug).+ */+export interface AbandonedSubAgentResume {+ parentOperationId: string;+ threadId: string;+ /** The parent's placeholder `role: 'tool'` message to backfill (= thread.sourceMessageId). */+ toolMessageId: string;+ userId: string;+ workspaceId?: string;+}+export interface FinalizeAbandonedResult {/** Whether the assistant message was successfully marked as errored. */assistantMessageUpdated: boolean;@@ -26,6 +43,11 @@ export interface FinalizeAbandonedResult {finalized: boolean;/** Whether agent state was found in Redis. */found: boolean;+ /**+ * Set when the abandoned op was a sub-agent parked under a parent's+ * `callSubAgent`. The caller MUST bridge this to resume the parent.+ */+ subAgentResume?: AbandonedSubAgentResume;}/**@@ -72,6 +94,9 @@ export class AbandonOperationService {const metadata = (state.metadata ?? {}) as {assistantMessageId?: string;+ isSubAgent?: boolean;+ orchestrationRole?: 'supervisor' | 'member';+ threadId?: string | null;userId?: string;workspaceId?: string;};@@ -118,10 +143,66 @@ export class AbandonOperationService {}}- try {- await this.coordinator.deleteAgentOperation(operationId);- } catch (e) {- log('[%s] coordinator cleanup failed (non-fatal): %O', operationId, e);+ // Resolve sub-agent β parent linkage. The watchdog killed this op without+ // firing its onComplete bridge, so a parent parked on `callSubAgent` would+ // otherwise wait on this slot forever. We surface the ids the caller needs+ // to backfill the placeholder tool message and CAS-resume the parent.+ // parentOperationId + threadId live on the (persistent) operation row;+ // toolMessageId is the thread's sourceMessageId (the parent's placeholder),+ // set when the sub-agent was dispatched. When this is set, the coordinator+ // cleanup below is SKIPPED so the durable resume can still resolve userId.+ //+ // Isolated group members ALSO run with `isSubAgent: true` and an isolation+ // thread, but their parent (supervisor) is resumed through the group K=N+ // bridge (`completeGroupActionMember`, driven by the member's own+ // `scheduleGroupMemberTimeout`) β routing them through the sub-agent bridge+ // would backfill the wrong message and never satisfy the group barrier. They+ // are tagged `orchestrationRole: 'member'`, so skip them here.+ if (metadata.isSubAgent && metadata.orchestrationRole !== 'member' && metadata.userId) {+ try {+ const opRow = await new AgentOperationModel(+ this.db,+ metadata.userId,+ metadata.workspaceId,+ ).findById(operationId);+ const parentOperationId = opRow?.parentOperationId ?? undefined;+ const threadId = opRow?.threadId ?? metadata.threadId ?? undefined;+ if (parentOperationId && threadId) {+ const thread = await new ThreadModel(+ this.db,+ metadata.userId,+ metadata.workspaceId,+ ).findById(threadId);+ const toolMessageId = thread?.sourceMessageId ?? undefined;+ if (toolMessageId) {+ result.subAgentResume = {+ parentOperationId,+ threadId,+ toolMessageId,+ userId: metadata.userId,+ workspaceId: metadata.workspaceId,+ };+ } else {+ log('[%s] sub-agent abandon: thread %s has no sourceMessageId', operationId, threadId);+ }+ }+ } catch (e) {+ // Non-fatal: the parent still has the bounded async-tool verify watchdog+ // as a fallback. Log so a failed resume hand-off stays observable.+ log('[%s] sub-agent parent-resume linkage lookup failed: %O', operationId, e);+ }+ }++ // Skip coordinator cleanup when a parent resume is still pending. The+ // durable subagent-callback (queue mode) re-resolves THIS op's userId from+ // the coordinator metadata, so deleting it now would 401 every redelivery+ // and strand the parent. The lingering state expires on its own Redis TTL.+ if (!result.subAgentResume) {+ try {+ await this.coordinator.deleteAgentOperation(operationId);+ } catch (e) {+ log('[%s] coordinator cleanup failed (non-fatal): %O', operationId, e);+ }}log('[%s] abandoned op finalized (reason=%s): %O', operationId, reason, result);diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex eba41cc3f2c..760853506ac 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -30,6 +30,16 @@ vi.mock('@/database/models/message', () => ({MessageModel: vi.fn().mockImplementation(() => ({ update: messageUpdateMock })),}));+const findOperationMock = vi.fn().mockResolvedValue(null);+vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn().mockImplementation(() => ({ findById: findOperationMock })),+}));++const findThreadMock = vi.fn().mockResolvedValue(null);+vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => ({ findById: findThreadMock })),+}));+const stateWith = (overrides: Record<string, any> = {}) => ({cost: { total: 0.1 },metadata: {@@ -47,6 +57,8 @@ const stateWith = (overrides: Record<string, any> = {}) => ({describe('AbandonOperationService', () => {beforeEach(() => {messageUpdateMock.mockClear();+ findOperationMock.mockReset().mockResolvedValue(null);+ findThreadMock.mockReset().mockResolvedValue(null);});it('returns found:false when coordinator has no state', async () => {@@ -203,4 +215,103 @@ describe('AbandonOperationService', () => {expect(result.finalized).toBe(true);expect(result.assistantMessageUpdated).toBe(false);});++ it('surfaces subAgentResume linkage when an abandoned op is a sub-agent', async () => {+ findOperationMock.mockResolvedValue({+ parentOperationId: 'op_parent',+ threadId: 'thread_1',+ });+ findThreadMock.mockResolvedValue({ sourceMessageId: 'msg_tool_placeholder' });++ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(+ stateWith({+ metadata: {+ assistantMessageId: 'msg_assist_1',+ isSubAgent: true,+ threadId: 'thread_1',+ userId: 'user_x',+ workspaceId: 'ws_1',+ },+ }),+ ),+ });+ const store = buildStore();+ store.loadPartial.mockResolvedValue(null);++ const svc = new AbandonOperationService({} as any, {+ coordinator: coord as any,+ snapshotStore: store as any,+ });++ const result = await svc.finalizeAbandoned('op_child', 'inactivity_watchdog');++ expect(result.subAgentResume).toEqual({+ parentOperationId: 'op_parent',+ threadId: 'thread_1',+ toolMessageId: 'msg_tool_placeholder',+ userId: 'user_x',+ workspaceId: 'ws_1',+ });+ // Coordinator state is kept alive so the durable parent-resume can still+ // resolve this op's userId; it expires via its own Redis TTL.+ expect(coord.deleteAgentOperation).not.toHaveBeenCalled();+ });++ it('omits subAgentResume for an isolated group member (orchestrationRole=member)', async () => {+ findOperationMock.mockResolvedValue({+ parentOperationId: 'op_supervisor',+ threadId: 'thread_g',+ });+ findThreadMock.mockResolvedValue({ sourceMessageId: 'msg_group_anchor' });++ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(+ stateWith({+ metadata: {+ assistantMessageId: 'msg_assist_1',+ isSubAgent: true,+ orchestrationRole: 'member',+ threadId: 'thread_g',+ userId: 'user_x',+ workspaceId: 'ws_1',+ },+ }),+ ),+ });+ const store = buildStore();+ store.loadPartial.mockResolvedValue(null);++ const svc = new AbandonOperationService({} as any, {+ coordinator: coord as any,+ snapshotStore: store as any,+ });++ const result = await svc.finalizeAbandoned('op_member', 'inactivity_watchdog');++ // Group members are resumed via the group K=N bridge (their own timeout),+ // not the sub-agent bridge β so we must NOT surface subAgentResume, and the+ // coordinator state is cleaned up normally.+ expect(result.subAgentResume).toBeUndefined();+ expect(findOperationMock).not.toHaveBeenCalled();+ expect(coord.deleteAgentOperation).toHaveBeenCalledWith('op_member');+ });++ it('omits subAgentResume for a non-sub-agent abandoned op', async () => {+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),+ });+ const store = buildStore();+ store.loadPartial.mockResolvedValue(null);++ const svc = new AbandonOperationService({} as any, {+ coordinator: coord as any,+ snapshotStore: store as any,+ });++ const result = await svc.finalizeAbandoned('op_x', 'reason');++ expect(result.subAgentResume).toBeUndefined();+ expect(findOperationMock).not.toHaveBeenCalled();+ });});diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 61ab72fa99c..7098646bad5 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -320,6 +320,13 @@ export interface OperationCreationParams {documentId?: string | null;groupId?: string | null;isSubAgent?: boolean;+ /**+ * Group orchestration role, spread onto `state.metadata.orchestrationRole`.+ * Lets the inactivity-watchdog abandon path tell an isolated group member+ * (`'member'`, resumed via the group K=N bridge) apart from a genuine+ * callSubAgent child (which shares `isSubAgent: true`).+ */+ orchestrationRole?: 'supervisor' | 'member';scope?: string | null;/** Source user message ID used for same-turn Agent Signal procedure suppression. */sourceMessageId?: string;diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex d0454a95a94..014598b3f39 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -2250,6 +2250,14 @@ export class AiAgentService {hasEnabledKnowledgeBases,isBotConversation,isGroupSupervisor,+ // Context-aware builtin manifests: inside a sub-agent (or group) run,+ // lobe-agent drops `callSubAgent` so the model can't recurse into nested+ // sub-agents (which the runtime rejects, looping until the inactivity+ // watchdog kills the op). Mirrors the frontend `createAgentToolsEngine`.+ manifestContext: {+ isSubAgent: appContext?.isSubAgent,+ scope: appContext?.scope ?? undefined,+ },model,provider,});@@ -3053,6 +3061,10 @@ export class AiAgentService {documentId: appContext?.documentId,groupId: appContext?.groupId,isSubAgent: appContext?.isSubAgent,+ // Persist the orchestration role on state.metadata so the+ // inactivity-watchdog abandon path can distinguish an isolated group+ // member ('member') from a genuine callSubAgent child.+ orchestrationRole: appContext?.orchestrationRole,scope: appContext?.scope,sourceMessageId: userMessageRecord?.id ?? parentMessageId ?? undefined,taskId: operationTaskId,@@ -3308,6 +3320,9 @@ export class AiAgentService {}),isSubAgent: true,logScope: 'execVirtualSubAgent',+ // Tag the op as a group member so the abandon path routes its parent+ // resume through the group bridge (its own timeout), not the sub-agent one.+ orchestrationRole: 'member',resumeParentOnComplete: true,},);@@ -3459,6 +3474,15 @@ export class AiAgentService {bridgeHookFactory?: (threadId: string) => AgentHook;isSubAgent: boolean;logScope: 'execSubAgent' | 'execVirtualSubAgent';+ /**+ * Marks the run's orchestration role on its operation metadata. Isolated+ * group members pass `'member'` so the inactivity-watchdog abandon path can+ * tell them apart from genuine `callSubAgent` children β both share+ * `isSubAgent: true` and an isolation thread, but a member's parent is+ * resumed through the group K=N bridge (via its own group-member timeout),+ * NOT `completeSubAgentBridge`.+ */+ orchestrationRole?: 'member';resumeParentOnComplete?: boolean;},): Promise<ExecSubAgentResult> {@@ -3546,6 +3570,7 @@ export class AiAgentService {const appContext: NonNullable<InternalExecAgentParams['appContext']> = {groupId,isSubAgent: options.isSubAgent,+ orchestrationRole: options.orchestrationRole,threadId: thread.id,topicId,};diff --git a/src/server/agent-hono/handlers/finalizeAbandoned.ts b/src/server/agent-hono/handlers/finalizeAbandoned.tsindex 9f8d7974a70..afc69c4e6ea 100644--- a/src/server/agent-hono/handlers/finalizeAbandoned.ts+++ b/src/server/agent-hono/handlers/finalizeAbandoned.ts@@ -3,6 +3,8 @@ import type { Context } from 'hono';import { getServerDB } from '@/database/core/db-adaptor';import { AbandonOperationService } from '@/server/services/agentRuntime';+import { deliverWebhook } from '@/server/services/agentRuntime/hooks/HookDispatcher';+import { AiAgentService } from '@/server/services/aiAgent';const log = debug('lobe-server:agent:finalize-abandoned');@@ -32,6 +34,57 @@ export async function finalizeAbandoned(c: Context): Promise<Response> {const service = new AbandonOperationService(serverDB);const result = await service.finalizeAbandoned(operationId, reason);+ // If the abandoned op was a sub-agent, resume its parent: the watchdog+ // killed the child without firing its onComplete bridge, so the parent+ // stays parked in `waiting_for_async_tool` until this runs.+ //+ // This endpoint is called by the DO inactivity watchdog EXACTLY ONCE and is+ // never retried, so the resume must carry its own durability. A transient+ // DB/Redis failure mid-bridge (the backfill in particular) cannot be+ // recovered by the parent's async-tool verify watchdog β that only re-reads+ // the barrier, it can't recreate the missing tool-message backfill. So in+ // queue mode we hand off to the same QStash-backed `/subagent-callback` the+ // normal completion path uses: QStash redelivers on non-2xx until the+ // backfill + CAS-resume land (the callback re-resolves userId from the+ // coordinator metadata, which `finalizeAbandoned` deliberately keeps alive+ // for sub-agent ops). In local/dev (no queue) we run the bridge inline.+ //+ // Failures intentionally propagate to the outer catch (β non-2xx) instead of+ // being swallowed behind a 200: a 200 here would falsely report the parent+ // as handled while it stays parked forever.+ if (result.subAgentResume) {+ const { parentOperationId, threadId, toolMessageId, userId, workspaceId } =+ result.subAgentResume;+ // Child reached a terminal failure (watchdog kill) β the bridge backfills+ // the parent's tool slot with an error note rather than a stub answer.+ const bridgeBody = {+ operationId,+ parentOperationId,+ reason: 'error',+ threadId,+ toolMessageId,+ };+ if (process.env.QSTASH_TOKEN) {+ await deliverWebhook(+ { delivery: 'qstash', fallback: 'none', url: '/api/agent/webhooks/subagent-callback' },+ bridgeBody,+ );+ log('[%s] queued durable parent-resume for %s', operationId, parentOperationId);+ } else {+ // No durable queue configured: run the CAS-guarded, idempotent bridge+ // inline through AiAgentService so the runtime's models stay+ // workspace-scoped.+ const aiAgentService = new AiAgentService(serverDB, userId, { workspaceId });+ const won = await aiAgentService.completeSubAgentBridge(bridgeBody);+ log(+ '[%s] resumed parent %s inline (local mode, won=%s)',+ operationId,+ parentOperationId,+ won,+ );+ }+ }+const executionTime = Date.now() - startTime;log('[%s] finalize-abandoned done in %dms: %O', operationId, executionTime, result);