🤯 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(lobe-agent): cancel a running sub-agent (#22496)
Lobehub Coder6d52b97abe13
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.tsindex fed29d59427..3849ca0c0a2 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts@@ -200,3 +200,56 @@ describe('runner builders fail closed for share-visitor runs', () => {).toBeUndefined();});});++describe('buildServerVirtualSubAgentRunner cancel', () => {+ const state = {+ operationId: 'parent-op',+ origin: { agentId: 'agent-1', topicId: 'topic-1' },+ } as AgentState;++ it('cancels only within the dispatching agent and topic', async () => {+ const cancelVirtualSubAgent = vi+ .fn()+ .mockResolvedValue({ status: 'cancelled', threadId: 'thread-1' });+ const ctx = {+ cancelVirtualSubAgent,+ execVirtualSubAgent: vi.fn(),+ messageModel: {},+ operationId: 'parent-op',+ topicId: 'topic-1',+ } as unknown as RuntimeExecutorContext;++ const runner = buildServerVirtualSubAgentRunner(+ ctx,+ state,+ { id: 'tool-call-1' } as ChatToolPayload,+ 'parent-message-1',+ );+ const result = await runner!.cancel!({ subAgentId: 'thread-1' });++ expect(cancelVirtualSubAgent).toHaveBeenCalledWith({+ agentId: 'agent-1',+ threadId: 'thread-1',+ topicId: 'topic-1',+ });+ expect(result).toEqual({ status: 'cancelled', threadId: 'thread-1' });+ });++ it('offers no cancel when the runtime cannot cancel', () => {+ const ctx = {+ execVirtualSubAgent: vi.fn(),+ messageModel: {},+ operationId: 'parent-op',+ topicId: 'topic-1',+ } as unknown as RuntimeExecutorContext;++ const runner = buildServerVirtualSubAgentRunner(+ ctx,+ state,+ { id: 'tool-call-1' } as ChatToolPayload,+ 'parent-message-1',+ );++ expect(runner?.cancel).toBeUndefined();+ });+});diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.tsindex 32c9b910e1c..008e3632b52 100644--- a/apps/server/src/modules/AgentRuntime/context.ts+++ b/apps/server/src/modules/AgentRuntime/context.ts@@ -1,6 +1,8 @@import { type AgentState } from '@lobechat/agent-runtime';import {type AgentShareVisitorContext,+ type CancelVirtualSubAgentParams,+ type CancelVirtualSubAgentResult,type ExecSubAgentParams,type ExecSubAgentResult,type ExecVirtualSubAgentParams,@@ -42,6 +44,13 @@ export interface RuntimeExecutorContext {*/allowEarlyFinalAnswerVisibleOutputEnd?: boolean;botContext?: unknown;+ /**+ * Callback to stop a running `lobe-agent.callSubAgent` child dispatched by+ * this run's agent (`lobe-agent.cancelSubAgent`).+ */+ cancelVirtualSubAgent?: (+ params: CancelVirtualSubAgentParams,+ ) => Promise<CancelVirtualSubAgentResult>;/*** Callback to fork a group member ("call agent member") under a* `lobe-group-management` tool call. Injected by AiAgentService; powers thediff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex e0643e8574c..33b1cdf229d 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -278,7 +278,12 @@ export const buildServerVirtualSubAgentRunner = (}: undefined;+ const cancelVirtualSubAgent = ctx.cancelVirtualSubAgent;+return {+ ...(cancelVirtualSubAgent && {+ cancel: ({ subAgentId }) => cancelVirtualSubAgent({ agentId, threadId: subAgentId, topicId }),+ }),run: async ({agentId: targetAgentId,background,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.tsindex d3c0ee4dd8e..788dd423c73 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.ts@@ -675,6 +675,9 @@ describe('AgentRuntimeService', () => {(service as any).messageModel.findById = vi.fn().mockResolvedValue({ id: 'tool-msg-1', topicId: 'topic-1' });+ (service as any).messageModel.releaseCancelSuppressedDelivery = vi+ .fn()+ .mockResolvedValue([]);deliver = vi.fn().mockResolvedValue(undefined);(service as any).delegate.deliverBackgroundSubAgentResults = deliver;});@@ -705,6 +708,35 @@ describe('AgentRuntimeService', () => {expect(deliver).toHaveBeenCalledWith({ topicId: 'topic-1' });});+ it('hands back a racing cancel claim when the run still finished with an answer', async () => {+ const release = vi.fn().mockResolvedValue(['tool-msg-1']);+ (service as any).messageModel.releaseCancelSuppressedDelivery = release;++ await service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any });++ expect(release).toHaveBeenCalledWith(['tool-msg-1']);+ // Released after the answer is stored and before it is delivered.+ expect(release.mock.invocationCallOrder[0]).toBeGreaterThan(+ updateToolMessage.mock.invocationCallOrder[0],+ );+ expect(release.mock.invocationCallOrder[0]).toBeLessThan(+ deliver.mock.invocationCallOrder[0],+ );+ });++ it('keeps a cancel claim when the run was stopped', async () => {+ const release = vi.fn().mockResolvedValue([]);+ (service as any).messageModel.releaseCancelSuppressedDelivery = release;++ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: childState as any,+ reason: 'interrupted',+ });++ expect(release).not.toHaveBeenCalled();+ });+it('stores a failure as an error result', async () => {await service.completeSubAgentBridge({...bridgeParams,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.tsindex 96a1cdc3ef6..ce29d978a6a 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts@@ -285,6 +285,7 @@ export async function createAgentRuntime(botContext: principal?.actor?.bot,execSubAgent: deps.delegate.execSubAgent,execVirtualSubAgent: deps.delegate.execVirtualSubAgent,+ cancelVirtualSubAgent: deps.delegate.cancelVirtualSubAgent,execGroupMember: deps.delegate.execGroupMember,onGroupMemberResult: (params) => deps.completeGroupMemberBarrier(params),hookDispatcher,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.tsindex 0f9ba7f85e3..b71505a9e0a 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.ts@@ -328,6 +328,16 @@ async function recordBackgroundSubAgentResult();}+ // A `cancelSubAgent` that raced this run claims the placeholder before it+ // interrupts, so the stop does not wake the parent. A run that still finished+ // with an answer hands that claim back here, once the answer is stored, so+ // the answer is delivered. A run the cancel did stop ends as an error and+ // stays suppressed. The release is conditional, so a redelivered callback or+ // the cancel's own check cannot hand back a real delivery's claim.+ if (status === 'completed') {+ await deps.messageModel.releaseCancelSuppressedDelivery([toolMessageId]);+ }+const placeholder = await deps.messageModel.findById(toolMessageId);if (!placeholder?.topicId || !deps.delegate.deliverBackgroundSubAgentResults) return;diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.tsindex 4c46ce55b57..8ffb37ca647 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts@@ -1,6 +1,8 @@import type { Agent, AgentState, GeneralAgentConfig } from '@lobechat/agent-runtime';import type { ISnapshotStore } from '@lobechat/agent-tracing';import {+ type CancelVirtualSubAgentParams,+ type CancelVirtualSubAgentResult,type ExecSubAgentParams,type ExecSubAgentResult,type ExecVirtualSubAgentParams,@@ -127,6 +129,14 @@ export interface InterventionLifecycleCheckpoint {* top-level option. One named home for the whole upward-call surface.*/export interface AgentRuntimeDelegate {+ /**+ * Stop a running `lobe-agent.callSubAgent` child on behalf of the agent that+ * dispatched it (`lobe-agent.cancelSubAgent`). The thread and its history are+ * kept, so the same sub-agent can be continued afterwards.+ */+ cancelVirtualSubAgent?: (+ params: CancelVirtualSubAgentParams,+ ) => Promise<CancelVirtualSubAgentResult>;/*** Hand the topic's finished background sub-agent results to their parent* agent as a new turn, unless a run of that topic is still going (its owndiff --git a/apps/server/src/services/aiAgent/__tests__/cancelSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/cancelSubAgent.test.tsnew file mode 100644index 00000000000..99b9d2503cc--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/cancelSubAgent.test.ts@@ -0,0 +1,249 @@+import { ThreadStatus, ThreadType } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { CancelSubAgentRunDeps, SubAgentRunDeps } from '../subAgentRuns';+import { cancelSubAgentThreadRun, execAgentThreadRun } from '../subAgentRuns';++const callSubAgentPlugin = { apiName: 'callSubAgent', identifier: 'lobe-agent' };++const subAgentThread = (overrides: Record<string, unknown> = {}) => ({+ agentId: 'agent-1',+ id: 'thread-1',+ metadata: { operationId: 'sub-op-1', startedAt: '2026-11-07T00:00:00.000Z' },+ sourceMessageId: 'placeholder-1',+ status: ThreadStatus.Processing,+ topicId: 'topic-1',+ type: ThreadType.Isolation,+ ...overrides,+});++const params = { agentId: 'agent-1', threadId: 'thread-1', topicId: 'topic-1' };++describe('cancelSubAgentThreadRun', () => {+ let deps: CancelSubAgentRunDeps;+ let messageModel: Record<string, ReturnType<typeof vi.fn>>;++ beforeEach(() => {+ messageModel = {+ claimBackgroundSubAgentDelivery: vi.fn(async (ids: string[]) => ids),+ findMessagePlugin: vi.fn(async (id: string) =>+ id === 'placeholder-1' ? callSubAgentPlugin : { ...callSubAgentPlugin, state: {} },+ ),+ listBackgroundSubAgentCalls: vi.fn().mockResolvedValue([]),+ releaseCancelSuppressedDelivery: vi.fn(async (ids: string[]) => ids),+ };+ deps = {+ agentOperationModel: { findById: vi.fn().mockResolvedValue({ status: 'running' }) } as any,+ interruptTask: vi.fn().mockResolvedValue({ success: true }),+ isOperationInterrupted: vi.fn().mockResolvedValue(true),+ messageModel: messageModel as any,+ stopWaitMs: 0,+ threadModel: { findById: vi.fn().mockResolvedValue(subAgentThread()) } as any,+ };+ });++ it('interrupts the running sub-agent of its thread', async () => {+ const result = await cancelSubAgentThreadRun(deps, params);++ expect(deps.interruptTask).toHaveBeenCalledWith({+ operationId: 'sub-op-1',+ threadId: 'thread-1',+ topicId: 'topic-1',+ });+ expect(result).toEqual({+ operationId: 'sub-op-1',+ status: 'cancelled',+ stopped: false,+ threadId: 'thread-1',+ });+ });++ it('reports the run stopped once its status leaves flight', async () => {+ vi.mocked(deps.agentOperationModel.findById)+ .mockResolvedValueOnce({ status: 'running' } as any)+ .mockResolvedValue({ status: 'interrupted' } as any);++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(result).toMatchObject({ status: 'cancelled', stopped: true });+ });++ it('hands the delivery back when the run ended on its own before the stop', async () => {+ messageModel.listBackgroundSubAgentCalls.mockResolvedValue([+ { id: 'bg-call-1', state: { background: true, status: 'pending', threadId: 'thread-1' } },+ ]);+ // A stop that finds the run already terminal acknowledges it without the mark.+ vi.mocked(deps.isOperationInterrupted).mockResolvedValue(false);++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(messageModel.releaseCancelSuppressedDelivery).toHaveBeenCalledWith(['bg-call-1']);+ expect(result.status).toBe('not_running');+ });++ it('marks a background run delivered so the stop does not wake the parent', async () => {+ messageModel.listBackgroundSubAgentCalls.mockResolvedValue([+ { id: 'bg-call-1', state: { background: true, status: 'pending', threadId: 'thread-1' } },+ { id: 'bg-call-2', state: { background: true, status: 'pending', threadId: 'thread-2' } },+ ]);++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(messageModel.listBackgroundSubAgentCalls).toHaveBeenCalledWith({+ scope: 'running',+ topicId: 'topic-1',+ });+ expect(messageModel.claimBackgroundSubAgentDelivery).toHaveBeenCalledWith(+ ['bg-call-1'],+ expect.any(String),+ { suppressedByCancel: true },+ );+ // The claim must land before the stop: the interrupted run's completion+ // delivers whatever is still unclaimed.+ expect(messageModel.claimBackgroundSubAgentDelivery.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(deps.interruptTask).mock.invocationCallOrder[0],+ );+ expect(messageModel.releaseCancelSuppressedDelivery).not.toHaveBeenCalled();+ expect(result.status).toBe('cancelled');+ });++ it('hands the delivery back when the run finished before the stop landed', async () => {+ messageModel.listBackgroundSubAgentCalls.mockResolvedValue([+ { id: 'bg-call-1', state: { background: true, status: 'pending', threadId: 'thread-1' } },+ ]);+ messageModel.findMessagePlugin.mockImplementation(async (id: string) =>+ id === 'placeholder-1'+ ? callSubAgentPlugin+ : { ...callSubAgentPlugin, state: { background: true, status: 'completed' } },+ );++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(messageModel.releaseCancelSuppressedDelivery).toHaveBeenCalledWith(['bg-call-1']);+ expect(result.status).toBe('not_running');+ });++ it('reports a run that finished while the stop was waiting as not cancelled', async () => {+ // The interrupt mark landed after the run's last check, so it still saved a+ // completed answer while cancel waited for it to leave flight.+ messageModel.listBackgroundSubAgentCalls.mockResolvedValue([+ { id: 'bg-call-1', state: { background: true, status: 'pending', threadId: 'thread-1' } },+ ]);+ let status = 'pending';+ messageModel.findMessagePlugin.mockImplementation(async (id: string) =>+ id === 'placeholder-1'+ ? callSubAgentPlugin+ : { ...callSubAgentPlugin, state: { background: true, status } },+ );+ vi.mocked(deps.agentOperationModel.findById)+ .mockResolvedValueOnce({ status: 'running' } as any)+ .mockImplementation(async () => {+ status = 'completed';+ return { status: 'done' } as any;+ });+ deps.stopWaitMs = 1000;++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(messageModel.releaseCancelSuppressedDelivery).toHaveBeenCalledWith(['bg-call-1']);+ expect(result.status).toBe('not_running');+ });++ it('hands the delivery back when the stop is not confirmed', async () => {+ messageModel.listBackgroundSubAgentCalls.mockResolvedValue([+ { id: 'bg-call-1', state: { background: true, status: 'pending', threadId: 'thread-1' } },+ ]);+ vi.mocked(deps.interruptTask).mockResolvedValue({ success: false });++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(messageModel.releaseCancelSuppressedDelivery).toHaveBeenCalledWith(['bg-call-1']);+ expect(result).toMatchObject({ status: 'failed', threadId: 'thread-1' });+ });++ it('hands the delivery back when the stop throws', async () => {+ messageModel.listBackgroundSubAgentCalls.mockResolvedValue([+ { id: 'bg-call-1', state: { background: true, status: 'pending', threadId: 'thread-1' } },+ ]);+ vi.mocked(deps.interruptTask).mockRejectedValue(new Error('redis down'));++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(messageModel.releaseCancelSuppressedDelivery).toHaveBeenCalledWith(['bg-call-1']);+ expect(result).toMatchObject({ error: 'Error: redis down', status: 'failed' });+ });++ it('stops nothing when the sub-agent already finished', async () => {+ vi.mocked(deps.agentOperationModel.findById).mockResolvedValue({ status: 'done' } as any);++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(deps.interruptTask).not.toHaveBeenCalled();+ expect(messageModel.claimBackgroundSubAgentDelivery).not.toHaveBeenCalled();+ expect(result).toEqual({+ operationId: 'sub-op-1',+ status: 'not_running',+ threadId: 'thread-1',+ });+ });++ it.each([+ ['another topic', { topicId: 'topic-2' }],+ ['another agent', { agentId: 'agent-2' }],+ ['a non-isolation thread', { type: ThreadType.Continuation }],+ ])('refuses a thread from %s', async (_, overrides) => {+ vi.mocked(deps.threadModel.findById).mockResolvedValue(subAgentThread(overrides) as any);++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(deps.interruptTask).not.toHaveBeenCalled();+ expect(result.status).toBe('failed');+ expect(result.error).toContain('was not found in this conversation');+ });++ it('refuses a thread that callSubAgent did not start', async () => {+ messageModel.findMessagePlugin.mockResolvedValue({+ apiName: 'callAgent',+ identifier: 'lobe-agent-management',+ });++ const result = await cancelSubAgentThreadRun(deps, params);++ expect(deps.interruptTask).not.toHaveBeenCalled();+ expect(result).toMatchObject({ status: 'failed' });+ expect(result.error).toContain('not a sub-agent started by callSubAgent');+ });+});++describe('continuing a sub-agent that is still stopping', () => {+ it('says the cancelled run is finishing its step instead of calling it busy', async () => {+ const isOperationInterrupted = vi.fn().mockResolvedValue(true);+ const deps = {+ agentOperationModel: { findById: vi.fn().mockResolvedValue({ status: 'running' }) },+ agentRuntimeService: { isOperationInterrupted },+ execAgent: vi.fn(),+ messageModel: { findMessagePlugin: vi.fn().mockResolvedValue(callSubAgentPlugin) },+ threadModel: { claimForRun: vi.fn(), findById: vi.fn().mockResolvedValue(subAgentThread()) },+ userId: 'user-1',+ } as unknown as SubAgentRunDeps;++ const result = await execAgentThreadRun(+ deps,+ {+ agentId: 'agent-1',+ instruction: 'Focus on the 2026 numbers instead',+ parentMessageId: 'placeholder-2',+ parentOperationId: '',+ threadId: 'thread-1',+ topicId: 'topic-1',+ },+ { isSubAgent: true, logScope: 'execVirtualSubAgent', resumeParentOnComplete: true },+ );++ expect(isOperationInterrupted).toHaveBeenCalledWith('sub-op-1');+ expect(result.success).toBe(false);+ expect(result.error).toContain('was cancelled and is still finishing its current step');+ expect(deps.threadModel.claimForRun).not.toHaveBeenCalled();+ expect(deps.execAgent).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex f9273673e5f..cf2ab82db38 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -5,6 +5,8 @@ import type { LobeChatDatabase } from '@lobechat/database';import type {AgentRunInitRequest,AgentSenderMetadata,+ CancelVirtualSubAgentParams,+ CancelVirtualSubAgentResult,ExecAgentResult,ExecGroupAgentParams,ExecGroupAgentResult,@@ -88,7 +90,12 @@ import { findOwnLiveRuns } from './steerQueue/liveRuns';import type { SubAgentLlmRelayRequest } from './subAgentLlmRelay';import { closeSubAgentLlmRelay, openSubAgentLlmRelay } from './subAgentLlmRelay';import type { SubAgentRunDeps } from './subAgentRuns';-import { execAgentMember, execAgentThreadRun, execIsolatedAgentMember } from './subAgentRuns';+import {+ cancelSubAgentThreadRun,+ execAgentMember,+ execAgentThreadRun,+ execIsolatedAgentMember,+} from './subAgentRuns';import type { InternalExecAgentParams } from './types';const log = debug('lobe-server:ai-agent-service');@@ -179,6 +186,7 @@ export class AiAgentService {//// Arrow fields are auto-bound, so no `.bind(this)`.delegate: {+ cancelVirtualSubAgent: this.cancelVirtualSubAgent,deliverBackgroundSubAgentResults: this.deliverBackgroundSubAgentResults,execSubAgent: this.execSubAgent,execVirtualSubAgent: this.execVirtualSubAgent,@@ -802,6 +810,24 @@ export class AiAgentService {resumeParentOnComplete: true,});+ /**+ * Stop a running `lobe-agent.callSubAgent` child for the agent that+ * dispatched it — see `cancelSubAgentThreadRun`. Runtime delegate entry.+ */+ cancelVirtualSubAgent = (+ params: CancelVirtualSubAgentParams,+ ): Promise<CancelVirtualSubAgentResult> =>+ cancelSubAgentThreadRun(+ {+ agentOperationModel: this.agentOperationModel,+ interruptTask: (p) => this.interruptTask(p),+ isOperationInterrupted: (operationId) => this.isOperationInterrupted(operationId),+ messageModel: this.messageModel,+ threadModel: this.threadModel,+ },+ params,+ );+/*** Hand a topic's finished background sub-agent results to their parent agent* as a new turn — see `backgroundSubAgentDelivery`. Runtime delegate entry.diff --git a/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts b/apps/server/src/services/aiAgent/shareGate/dispatch.test.tsindex 659a276afef..c0d66f67dce 100644--- a/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts+++ b/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts@@ -221,6 +221,13 @@ describe('isShareBlockedBuiltinDispatch', () => {LobeAgentApiName.callSubAgent,),).toBe(true);+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: LobeAgentIdentifier }] },+ LobeAgentIdentifier,+ LobeAgentApiName.cancelSubAgent,+ ),+ ).toBe(true);});it('still applies the data-tool rules after the enable check', () => {diff --git a/apps/server/src/services/aiAgent/shareGate/dispatch.ts b/apps/server/src/services/aiAgent/shareGate/dispatch.tsindex 31d6d5cab41..b4201824da6 100644--- a/apps/server/src/services/aiAgent/shareGate/dispatch.ts+++ b/apps/server/src/services/aiAgent/shareGate/dispatch.ts@@ -98,7 +98,7 @@ export const isShareBlockedBuiltinDispatch = (// that does NOT thread the parent's shareGate — the child would run with// the creator's full, unrestricted tool surface. Assembly strips the API// (`stripSubAgentDispatchApis`); this is its dispatch-time counterpart.- if (SUB_AGENT_DISPATCH_APIS[identifier]?.apiName === apiName) return true;+ if (SUB_AGENT_DISPATCH_APIS[identifier]?.apiNames.has(apiName)) return true;// `humanIntervention` is deliberately NOT re-checked here: share runs keep// the manifest's intervention config and honor the visitor's own approvaldiff --git a/apps/server/src/services/aiAgent/shareGate/subAgentDispatch.ts b/apps/server/src/services/aiAgent/shareGate/subAgentDispatch.tsindex bb76ed50da8..4c4985a0a70 100644--- a/apps/server/src/services/aiAgent/shareGate/subAgentDispatch.ts+++ b/apps/server/src/services/aiAgent/shareGate/subAgentDispatch.ts@@ -1,5 +1,5 @@import {- LobeAgentApiName,+ LOBE_AGENT_SUB_AGENT_APIS,LobeAgentIdentifier,systemPromptWithoutSubAgent,} from '@lobechat/builtin-tool-lobe-agent';@@ -12,7 +12,7 @@ import type { ShareGateToolSet } from './types';* Sub-agent dispatch is not available in shared visitor runs. This strip runs* unconditionally on `lobe-agent`, independent of whether the manifest was* resolved through the normal context-aware path, so a whitelisted entry can- * never surface `callSubAgent` — nor a `systemRole` that instructs the model+ * never surface `callSubAgent` / `cancelSubAgent` — nor a `systemRole` that instructs the model* to call it — to a share visitor's model or the activator. `lobe-agent`* already ships a precise systemRole variant without the dispatch section* (`systemPromptWithoutSubAgent`, also used by its own context-aware@@ -24,16 +24,16 @@ import type { ShareGateToolSet } from './types';*/export const SUB_AGENT_DISPATCH_APIS: Record<string,- { apiName: string; systemRoleWithoutDispatch: string }+ { apiNames: ReadonlySet<string>; systemRoleWithoutDispatch: string }> = {[LobeAgentIdentifier]: {- apiName: LobeAgentApiName.callSubAgent,+ apiNames: LOBE_AGENT_SUB_AGENT_APIS,systemRoleWithoutDispatch: systemPromptWithoutSubAgent,},};export const stripSubAgentDispatchApis = (toolSet: ShareGateToolSet): void => {- for (const [identifier, { apiName, systemRoleWithoutDispatch }] of Object.entries(+ for (const [identifier, { apiNames, systemRoleWithoutDispatch }] of Object.entries(SUB_AGENT_DISPATCH_APIS,)) {const manifest = toolSet.manifestMap[identifier];@@ -44,14 +44,16 @@ export const stripSubAgentDispatchApis = (toolSet: ShareGateToolSet): void => {// still instructs the model to call the removed tool.toolSet.manifestMap[identifier] = {...manifest,- api: manifest.api.filter((api) => api.name !== apiName),+ api: manifest.api.filter((api) => !apiNames.has(api.name)),systemRole: systemRoleWithoutDispatch,};}if (toolSet.tools) {- const dispatchToolName = `${identifier}${PLUGIN_SCHEMA_SEPARATOR}${apiName}`;- pruneArrayInPlace(toolSet.tools, (tool) => tool?.function?.name !== dispatchToolName);+ const dispatchToolNames = new Set(+ [...apiNames].map((apiName) => `${identifier}${PLUGIN_SCHEMA_SEPARATOR}${apiName}`),+ );+ pruneArrayInPlace(toolSet.tools, (tool) => !dispatchToolNames.has(tool?.function?.name));}}};diff --git a/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.test.tsindex 0f236d378fd..353db4747cf 100644--- a/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts@@ -207,7 +207,11 @@ describe('applyShareGateToToolSet', () => {it('strips callSubAgent and pins the dispatch-free systemRole', () => {const toolSet = buildToolSet([{- apis: [{ name: LobeAgentApiName.callSubAgent }, { name: LobeAgentApiName.analyzeMedia }],+ apis: [+ { name: LobeAgentApiName.callSubAgent },+ { name: LobeAgentApiName.cancelSubAgent },+ { name: LobeAgentApiName.analyzeMedia },+ ],identifier: LobeAgentIdentifier,},]);@@ -218,11 +222,11 @@ describe('applyShareGateToToolSet', () => {);const manifest = toolSet.manifestMap[LobeAgentIdentifier];- expect(manifest.api.map((api) => api.name)).not.toContain(LobeAgentApiName.callSubAgent);+ expect(manifest.api.map((api) => api.name)).toEqual([LobeAgentApiName.analyzeMedia]);expect(manifest.systemRole).toBe(systemPromptWithoutSubAgent);- expect(toolSet.tools!.map((tool: any) => tool.function.name)).not.toContain(- toolName(LobeAgentIdentifier, LobeAgentApiName.callSubAgent),- );+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName(LobeAgentIdentifier, LobeAgentApiName.analyzeMedia),+ ]);});it('drops a memory tool without allowReadMemory and strips its writes with it', () => {diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.tsindex 08b3a086f35..05a648df449 100644--- a/apps/server/src/services/aiAgent/subAgentRuns.ts+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts@@ -1,6 +1,8 @@import type { AgentRunLlmExecutor } from '@lobechat/agent-runtime';import { isCallSubAgentCall } from '@lobechat/builtin-tool-lobe-agent';import type {+ CancelVirtualSubAgentParams,+ CancelVirtualSubAgentResult,ExecAgentResult,ExecSubAgentParams,ExecSubAgentResult,@@ -127,11 +129,11 @@ type ThreadRow = NonNullable<Awaited<ReturnType<ThreadModel['findById']>>>;* accumulated so far); the claim and every later write of this run carry it* forward instead of resetting it.*/-const claimSubAgentThread = async (- deps: SubAgentRunDeps,- params: { agentId: string; startedAt: string; threadId: string; topicId: string },-): Promise<{ error: string } | { thread: ThreadRow; carryOver: ThreadCarryOver }> => {- const { agentId, startedAt, threadId, topicId } = params;+const findCallSubAgentThread = async (+ deps: Pick<SubAgentRunDeps, 'messageModel' | 'threadModel'>,+ params: { agentId: string; threadId: string; topicId: string },+): Promise<{ error: string } | { thread: ThreadRow }> => {+ const { agentId, threadId, topicId } = params;const thread = await deps.threadModel.findById(threadId);if (@@ -152,19 +154,64 @@ const claimSubAgentThread = async (return { error: `"${threadId}" is not a sub-agent started by callSubAgent.` };}+ return { thread };+};++/**+ * The thread's latest run and whether it is still going. The operation, not+ * the thread row's own `status`, is authoritative: the inactivity watchdog+ * abandons a stuck operation without touching its thread.+ */+const readSubAgentThreadRun = async (+ deps: Pick<SubAgentRunDeps, 'agentOperationModel'>,+ thread: ThreadRow,+): Promise<{ operationId?: string; running: boolean }> => {+ const operationId = (thread.metadata as ThreadMetadata | null)?.operationId;+ const operation = operationId ? await deps.agentOperationModel.findById(operationId) : null;++ return {+ operationId,+ running: operation+ ? isAgentOperationInFlight(operation.status)+ : thread.status === ThreadStatus.Processing,+ };+};++/** Best-effort: a failed probe only loses the more precise busy message. */+const isStopping = async (deps: SubAgentRunDeps, operationId: string): Promise<boolean> => {+ try {+ return await deps.agentRuntimeService.isOperationInterrupted(operationId);+ } catch {+ return false;+ }+};++const claimSubAgentThread = async (+ deps: SubAgentRunDeps,+ params: { agentId: string; startedAt: string; threadId: string; topicId: string },+): Promise<{ error: string } | { thread: ThreadRow; carryOver: ThreadCarryOver }> => {+ const { agentId, startedAt, threadId, topicId } = params;+ const found = await findCallSubAgentThread(deps, { agentId, threadId, topicId });+ if ('error' in found) return found;++ const { thread } = found;const previousMetadata = thread.metadata as ThreadMetadata | null;- const previousOperationId = previousMetadata?.operationId;- const previousOperation = previousOperationId- ? await deps.agentOperationModel.findById(previousOperationId)- : null;- // The operation, not the thread row's own `status`, is authoritative: the- // inactivity watchdog abandons a stuck operation without touching its thread.- const stillRunning = previousOperation- ? isAgentOperationInFlight(previousOperation.status)- : thread.status === ThreadStatus.Processing;+ const { operationId: previousOperationId, running: stillRunning } = await readSubAgentThreadRun(+ deps,+ thread,+ );const busyError = `Sub-agent "${threadId}" is still running. Wait for its result before sending it another instruction.`;- if (stillRunning) return { error: busyError };+ if (stillRunning) {+ // A cancelled run only stops at its next step boundary, so a follow-up sent+ // right after cancelSubAgent can still find it live.+ if (previousOperationId && (await isStopping(deps, previousOperationId))) {+ return {+ error: `Sub-agent "${threadId}" was cancelled and is still finishing its current step. Send this instruction again in a moment; its history is kept.`,+ };+ }+ return { error: busyError };+ }const carryOver = pickThreadCarryOver(previousMetadata);const claimed = await deps.threadModel.claimForRun(@@ -176,6 +223,151 @@ const claimSubAgentThread = async (return claimed ? { thread, carryOver } : { error: busyError };};+export interface CancelSubAgentRunDeps extends Pick<+ SubAgentRunDeps,+ 'agentOperationModel' | 'messageModel' | 'threadModel'+> {+ /** The facade's `interruptTask` — the same stop a user's Stop button runs. */+ interruptTask: (params: {+ operationId?: string;+ threadId?: string;+ topicId?: string;+ }) => Promise<{ success: boolean }>;+ /** Whether the run carries the interrupt mark (set only by a stop that caught it live). */+ isOperationInterrupted: (operationId: string) => Promise<boolean>;+ /** How long to wait for the stopped run to reach a terminal status; tests pass 0. */+ stopWaitMs?: number;+}++const STOP_WAIT_MS = 10_000;+const STOP_POLL_MS = 500;++/** Poll the run's durable status until it is no longer in flight, up to `timeoutMs`. */+const waitForRunToStop = async (+ deps: Pick<CancelSubAgentRunDeps, 'agentOperationModel'>,+ operationId: string,+ timeoutMs: number,+): Promise<boolean> => {+ const deadline = Date.now() + timeoutMs;+ while (true) {+ const operation = await deps.agentOperationModel.findById(operationId).catch(() => null);+ if (operation && !isAgentOperationInFlight(operation.status)) return true;+ if (Date.now() + STOP_POLL_MS > deadline) return false;+ await new Promise((resolve) => setTimeout(resolve, STOP_POLL_MS));+ }+};++/**+ * Stop a running `callSubAgent` child on behalf of the agent that dispatched it+ * (`lobe-agent.cancelSubAgent`). Only the dispatcher's own sub-agents in the+ * same topic can be cancelled.+ *+ * The run is interrupted like a user Stop: it ends at its next step boundary+ * and its thread turns `cancel`. Its history stays on the thread, so the parent+ * can steer it afterwards with `callSubAgent({ subAgentId })`.+ *+ * A background run's answer is normally delivered to the parent as a new turn.+ * The parent asked for this stop and already holds the result of this call, so+ * the run's placeholder is marked delivered first — otherwise the stop would+ * wake the parent with a "did not complete (interrupted)" message. When the+ * run turns out to have finished before the stop landed, the mark is taken+ * back so its real answer is still delivered.+ */+export const cancelSubAgentThreadRun = async (+ deps: CancelSubAgentRunDeps,+ params: CancelVirtualSubAgentParams,+): Promise<CancelVirtualSubAgentResult> => {+ const { agentId, threadId, topicId } = params;++ const found = await findCallSubAgentThread(deps, { agentId, threadId, topicId });+ if ('error' in found) return { error: found.error, status: 'failed', threadId };++ const { operationId, running } = await readSubAgentThreadRun(deps, found.thread);+ if (!running || !operationId) return { operationId, status: 'not_running', threadId };++ const backgroundCalls = (+ await deps.messageModel.listBackgroundSubAgentCalls({ scope: 'running', topicId })+ ).filter((call) => call.state.threadId === threadId);+ const suppressed = await deps.messageModel.claimBackgroundSubAgentDelivery(+ backgroundCalls.map((call) => call.id),+ new Date().toISOString(),+ { suppressedByCancel: true },+ );+ // Only hands back this cancel's own claims: the run's completion releases+ // them too when it still records an answer (see `completeSubAgentBridge`).+ const restoreDelivery = (ids: string[]) =>+ deps.messageModel+ .releaseCancelSuppressedDelivery(ids)+ .catch((error) => log('cancelSubAgent: failed to restore delivery of %O: %O', ids, error));++ let interrupted: { success: boolean };+ try {+ interrupted = await deps.interruptTask({ operationId, threadId, topicId });+ } catch (error) {+ await restoreDelivery(suppressed);+ log('cancelSubAgent: interrupting %s failed: %O', operationId, error);+ return { error: String(error), operationId, status: 'failed', threadId };+ }++ if (!interrupted.success) {+ await restoreDelivery(suppressed);+ return {+ error: 'The sub-agent could not be confirmed as stopped.',+ operationId,+ status: 'failed',+ threadId,+ };+ }++ // The run may have ended on its own between the liveness read and the stop:+ // `interruptOperation` then acknowledges the terminal state without setting+ // the interrupt sentinel, and its completion records a real answer that must+ // still reach the parent.+ const stoppedByUs = await deps.isOperationInterrupted(operationId).catch((error) => {+ log('cancelSubAgent: reading the interrupt mark of %s failed: %O', operationId, error);+ return false;+ });+ if (!stoppedByUs) {+ await restoreDelivery(suppressed);+ return { operationId, status: 'not_running', threadId };+ }+ const findFinished = async (): Promise<string[]> => {+ const finished: string[] = [];+ for (const id of suppressed) {+ const plugin = await deps.messageModel.findMessagePlugin(id).catch((error) => {+ log('cancelSubAgent: reading placeholder %s failed: %O', id, error);+ return undefined;+ });+ if ((plugin?.state as { status?: string } | undefined)?.status === 'completed') {+ finished.push(id);+ }+ }+ return finished;+ };+ const finishedBeforeStop = await findFinished();+ if (finishedBeforeStop.length > 0) {+ await restoreDelivery(finishedBeforeStop);+ return { operationId, status: 'not_running', threadId };+ }++ // The run only ends at its next step boundary. Waiting for it lets the parent+ // steer the sub-agent right away: a follow-up is refused while it still runs,+ // and nothing would tell the parent when it finally stopped.+ const stopped = await waitForRunToStop(deps, operationId, deps.stopWaitMs ?? STOP_WAIT_MS);++ // The interrupt mark can land after the run's last check but before it saves+ // its end state, so the run may still finish with an answer. Its completion+ // hands the claim back; this only reports it when that already happened.+ const finishedDuringStop = await findFinished();+ if (finishedDuringStop.length > 0) {+ await restoreDelivery(finishedDuringStop);+ return { operationId, status: 'not_running', threadId };+ }++ log('cancelSubAgent: cancelled %s on thread %s (stopped=%s)', operationId, threadId, stopped);+ return { operationId, status: 'cancelled', stopped, threadId };+};+/*** Execute an agent in an isolated Thread context: create the isolation thread,* register thread-lifecycle (and optionally completion-bridge) hooks, delegatediff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.cancelSubAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.cancelSubAgent.test.tsnew file mode 100644index 00000000000..df48ab9e859--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.cancelSubAgent.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it, vi } from 'vitest';++import type { ToolExecutionContext } from '../../types';++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return {};+ }),+}));++const { lobeAgentRuntime } = await import('../lobeAgent');++describe('lobeAgentRuntime cancelSubAgent', () => {+ const context = {+ messageId: 'msg-1',+ serverDB: {} as any,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ } as ToolExecutionContext;++ const withCancel = (cancel: ReturnType<typeof vi.fn>) =>+ ({ ...context, subAgent: { cancel, run: vi.fn() } }) as ToolExecutionContext;++ it('cancels the sub-agent and tells the parent how to steer it', async () => {+ const cancel = vi.fn().mockResolvedValue({+ operationId: 'sub-op-1',+ status: 'cancelled',+ stopped: true,+ threadId: 'thread-1',+ });+ const runtime = lobeAgentRuntime.factory(context);++ const result = await runtime.cancelSubAgent(+ { reason: 'The user no longer needs it', subAgentId: ' thread-1 ' },+ withCancel(cancel),+ );++ expect(cancel).toHaveBeenCalledWith({ subAgentId: 'thread-1' });+ expect(result).toMatchObject({+ state: { status: 'cancelled', threadId: 'thread-1' },+ success: true,+ });+ expect(result.content).toContain('cancelled');+ expect(result.content).toMatch(/no result will be delivered/i);+ expect(result.content).toContain('callSubAgent with subAgentId "thread-1"');+ expect(result.content).toContain('stopped');+ });++ it('tells the parent to wait for a sub-agent still finishing its step', async () => {+ const cancel = vi.fn().mockResolvedValue({+ status: 'cancelled',+ stopped: false,+ threadId: 'thread-1',+ });+ const runtime = lobeAgentRuntime.factory(context);++ const result = await runtime.cancelSubAgent({ subAgentId: 'thread-1' }, withCancel(cancel));++ expect(result).toMatchObject({ state: { status: 'cancelled' }, success: true });+ expect(result.content).toContain('still finishing its current step');+ expect(result.content).toContain('once it has stopped');+ });++ it('reports a sub-agent that is no longer running without failing', async () => {+ const cancel = vi.fn().mockResolvedValue({ status: 'not_running', threadId: 'thread-1' });+ const runtime = lobeAgentRuntime.factory(context);++ const result = await runtime.cancelSubAgent({ subAgentId: 'thread-1' }, withCancel(cancel));++ expect(result).toMatchObject({+ state: { status: 'not_running', threadId: 'thread-1' },+ success: true,+ });+ expect(result.content).toContain('not running');+ });++ it('surfaces a refused cancel as a tool error', async () => {+ const cancel = vi.fn().mockResolvedValue({+ error: 'Sub-agent "thread-9" was not found in this conversation.',+ status: 'failed',+ threadId: 'thread-9',+ });+ const runtime = lobeAgentRuntime.factory(context);++ const result = await runtime.cancelSubAgent({ subAgentId: 'thread-9' }, withCancel(cancel));++ expect(result).toMatchObject({ error: { code: 'SUB_AGENT_CANCEL_FAILED' }, success: false });+ expect(result.content).toContain('was not found in this conversation');+ });++ it.each([[''], [' '], [undefined], [42]])(+ 'rejects a missing subAgentId (%s) without cancelling anything',+ async (subAgentId) => {+ const cancel = vi.fn();+ const runtime = lobeAgentRuntime.factory(context);++ const result = await runtime.cancelSubAgent(+ { subAgentId: subAgentId as any },+ withCancel(cancel),+ );++ expect(result).toMatchObject({ error: { code: 'INVALID_ARGUMENTS' }, success: false });+ expect(cancel).not.toHaveBeenCalled();+ },+ );++ it('refuses inside a sub-agent', async () => {+ const cancel = vi.fn();+ const runtime = lobeAgentRuntime.factory(context);++ const result = await runtime.cancelSubAgent({ subAgentId: 'thread-1' }, {+ ...withCancel(cancel),+ isSubAgent: true,+ } as ToolExecutionContext);++ expect(result).toMatchObject({ error: { code: 'NESTED_SUB_AGENT_NOT_ALLOWED' } });+ expect(cancel).not.toHaveBeenCalled();+ });++ it('refuses when the runtime cannot cancel', async () => {+ const runtime = lobeAgentRuntime.factory(context);++ const result = await runtime.cancelSubAgent({ subAgentId: 'thread-1' }, {+ ...context,+ subAgent: { run: vi.fn() },+ } as ToolExecutionContext);++ expect(result).toMatchObject({ error: { code: 'SUB_AGENT_UNAVAILABLE' }, success: false });+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.tsindex 689159f1409..ad2f465838b 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -1,6 +1,8 @@import type {AnalyzeMediaParams,CallSubAgentParams,+ CancelSubAgentParams,+ CancelSubAgentState,MediaFileItem,MediaSourceMessage,VentParams,@@ -386,6 +388,62 @@ class LobeAgentExecutionRuntime {};};+ /**+ * Stop a running sub-agent this agent dispatched earlier in the conversation.+ * Cancelling it before it reports back keeps the stop from waking this agent+ * again with a "did not complete" result (see `cancelSubAgentThreadRun`).+ */+ cancelSubAgent = async (+ params: CancelSubAgentParams,+ ctx: ToolExecutionContext,+ ): Promise<BuiltinServerRuntimeOutput> => {+ if (ctx.isSubAgent) {+ return buildError(+ 'Sub-agents cannot be cancelled from within another sub-agent.',+ 'NESTED_SUB_AGENT_NOT_ALLOWED',+ );+ }+ if (!ctx.subAgent?.cancel) {+ return buildError(+ 'Cancelling a sub-agent is not available in this runtime.',+ 'SUB_AGENT_UNAVAILABLE',+ );+ }+ const subAgentId = typeof params.subAgentId === 'string' ? params.subAgentId.trim() : '';+ if (!subAgentId) {+ return buildError(+ 'subAgentId is required: pass the id from the sub-agent\'s <sub_agent id="..." /> tag.',+ 'INVALID_ARGUMENTS',+ );+ }++ const result = await ctx.subAgent.cancel({ subAgentId });++ if (result.status === 'failed') {+ return buildError(+ `Sub-agent "${subAgentId}" could not be cancelled: ${result.error ?? 'unknown error'}`,+ 'SUB_AGENT_CANCEL_FAILED',+ );+ }++ const state: CancelSubAgentState = { status: result.status, threadId: result.threadId };+ if (result.status === 'not_running') {+ return {+ content: `Sub-agent "${subAgentId}" is not running, so there was nothing to cancel. If it already finished, its result is (or will be) delivered as usual.`,+ state,+ success: true,+ };+ }++ return {+ content: result.stopped+ ? `Sub-agent "${subAgentId}" cancelled and stopped. No result will be delivered for it. Its history is kept: to steer it, call callSubAgent with subAgentId "${subAgentId}" and a corrected instruction.`+ : `Sub-agent "${subAgentId}" cancelled. It is still finishing its current step and stops after it; no result will be delivered for it. Its history is kept: once it has stopped, call callSubAgent with subAgentId "${subAgentId}" and a corrected instruction to steer it.`,+ state,+ success: true,+ };+ };+// ==================== Vent ====================vent = async (diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex 0f2dd63e5a2..63fde17ac77 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -2,6 +2,7 @@ import { type LobeToolManifest } from '@lobechat/context-engine';import { type LobeChatDatabase } from '@lobechat/database';import {type AgentShareVisitorContext,+ type CancelVirtualSubAgentResult,type ChatToolPayload,type ChatTopicBotContext,type ClientSecretPayload,@@ -85,6 +86,11 @@ export interface ServerSubAgentRunResult {* the completion bridge, which backfills the placeholder and resumes the parent.*/export interface ServerSubAgentRunner {+ /**+ * Stop a running `callSubAgent` sub-agent this run's agent dispatched in the+ * same topic (`cancelSubAgent`). Absent when the runtime cannot cancel.+ */+ cancel?: (params: { subAgentId: string }) => Promise<CancelVirtualSubAgentResult>;run: (params: ServerSubAgentRunParams) => Promise<ServerSubAgentRunResult>;}diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 718c041f793..c7c512dfbcf 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -219,6 +219,7 @@"builtins.lobe-agent.apiName.analyzeMedia.mediaCount": "{{count}} media","builtins.lobe-agent.apiName.analyzeMedia.result": "Analyze media: <question>{{question}}</question>","builtins.lobe-agent.apiName.callSubAgent": "Call sub-agent",+ "builtins.lobe-agent.apiName.cancelSubAgent": "Cancel sub-agent","builtins.lobe-agent.apiName.clearTodos": "Clear todos","builtins.lobe-agent.apiName.clearTodos.modeAll": "all","builtins.lobe-agent.apiName.clearTodos.modeCompleted": "completed",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 561590d3a76..d5ac195b79d 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -219,6 +219,7 @@"builtins.lobe-agent.apiName.analyzeMedia.mediaCount": "{{count}} 个媒体","builtins.lobe-agent.apiName.analyzeMedia.result": "分析媒体:<question>{{question}}</question>","builtins.lobe-agent.apiName.callSubAgent": "调用子助理",+ "builtins.lobe-agent.apiName.cancelSubAgent": "取消子助理","builtins.lobe-agent.apiName.clearTodos": "清除待办","builtins.lobe-agent.apiName.clearTodos.modeAll": "全部","builtins.lobe-agent.apiName.clearTodos.modeCompleted": "已完成",diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.tsindex 32e8e35349e..56bbc953c2d 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts@@ -29,6 +29,7 @@ import type {AnalyzeMediaParams,AskUserQuestionArgs,CallSubAgentParams,+ CancelSubAgentParams,ClearTodosParams,CreatePlanParams,CreateTodosParams,@@ -538,6 +539,21 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {success: true,};};++ // Client-run sub-agents block the turn that dispatched them, so none of them+ // is ever still running when the model could ask to cancel it. Cancelling a+ // background sub-agent is implemented by the server runtime only.+ cancelSubAgent = async (+ _params: CancelSubAgentParams,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ if (ctx.isSubAgent) return nestedSubAgentDisabledResult();++ return {+ content: 'Cancelling a sub-agent is not supported in this runtime.',+ success: false,+ };+ };}export const lobeAgentExecutor = new LobeAgentExecutor();diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.tsindex 671df279971..342fd0bc775 100644--- a/packages/builtin-tool-lobe-agent/src/manifest.ts+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts@@ -277,6 +277,27 @@ export const LobeAgentManifest: BuiltinToolManifest = {type: 'object',},},+ {+ description:+ 'Cancel a sub-agent that is still running — one started with `runInBackground`, or one whose work is no longer needed or has gone off track. It stops at its next step, no result is delivered for it, and its history is kept: to steer it instead of abandoning it, cancel it, then send a corrected instruction with `callSubAgent` and the same `subAgentId`.',+ name: LobeAgentApiName.cancelSubAgent,+ parameters: {+ additionalProperties: false,+ properties: {+ subAgentId: {+ description:+ 'The id from the `<sub_agent id="..." />` tag of the sub-agent to cancel. Never invent an id.',+ type: 'string',+ },+ reason: {+ description: 'Optional. One short sentence on why it is no longer needed.',+ type: 'string',+ },+ },+ required: ['subAgentId'],+ type: 'object',+ },+ },{description:'Privately report friction in your own working conditions to the platform builders when you are genuinely blocked — a missing tool, a parameter/schema mismatch, conflicting or wrong docs, anomalous platform behavior, or an environment limit causing repeated failure. Not user-facing; it only records the report and does not fix anything. Use sparingly: at most one vent per run, only for the single worst blocker. It never stops a tool loop or ends your turn — to stop, just reply to the user; repeated or empty vents are rejected.',diff --git a/packages/builtin-tool-lobe-agent/src/resolveManifest.test.ts b/packages/builtin-tool-lobe-agent/src/resolveManifest.test.tsindex 13abdba271c..01502205a8e 100644--- a/packages/builtin-tool-lobe-agent/src/resolveManifest.test.ts+++ b/packages/builtin-tool-lobe-agent/src/resolveManifest.test.ts@@ -29,12 +29,13 @@ describe('resolveLobeAgentManifest', () => {const names = apiNames(result);expect(names).not.toContain(LobeAgentApiName.callSubAgent);+ expect(names).not.toContain(LobeAgentApiName.cancelSubAgent);// the rest of lobe-agent stays availableexpect(names).toContain(LobeAgentApiName.createPlan);expect(names).toContain(LobeAgentApiName.createTodos);expect(names).toContain(LobeAgentApiName.analyzeMedia);- // exactly one API removed- expect(names).toHaveLength(LobeAgentManifest.api.length - 1);+ // exactly the two sub-agent APIs removed+ expect(names).toHaveLength(LobeAgentManifest.api.length - 2);// systemRole is rewritten so the prompt no longer mentions the hidden toolexpect(result.systemRole).toBe(systemPromptWithoutSubAgent);@@ -52,8 +53,10 @@ describe('resolveLobeAgentManifest', () => {const result = resolveLobeAgentManifest({ isSubAgent: true, scope: 'main' })!;expect(apiNames(result)).not.toContain(LobeAgentApiName.callSubAgent);+ expect(apiNames(result)).not.toContain(LobeAgentApiName.cancelSubAgent);expect(apiNames(result)).toContain(LobeAgentApiName.createPlan);expect(result.systemRole).not.toContain('callSubAgent');+ expect(result.systemRole).not.toContain('cancelSubAgent');});it('does not mutate the original static manifest', () => {diff --git a/packages/builtin-tool-lobe-agent/src/resolveManifest.ts b/packages/builtin-tool-lobe-agent/src/resolveManifest.tsindex e33d19c0420..f6b05d6ad86 100644--- a/packages/builtin-tool-lobe-agent/src/resolveManifest.ts+++ b/packages/builtin-tool-lobe-agent/src/resolveManifest.ts@@ -4,6 +4,15 @@ import { LobeAgentManifest } from './manifest';import { systemPromptWithoutSubAgent } from './systemRole';import { LobeAgentApiName } from './types';+/**+ * Sub-agent dispatch and control: hidden together, never one without the other.+ * The share-visitor gate strips the same set.+ */+export const LOBE_AGENT_SUB_AGENT_APIS: ReadonlySet<string> = new Set<string>([+ LobeAgentApiName.callSubAgent,+ LobeAgentApiName.cancelSubAgent,+]);+/*** Context-aware manifest for the lobe-agent tool.*@@ -18,7 +27,7 @@ import { LobeAgentApiName } from './types';** In both cases plan / todo / media-analysis APIs stay available, so this returns a* trimmed manifest (not `null`). It rewrites BOTH halves of the manifest in step:- * the `api` list drops `callSubAgent`, and `systemRole` switches to the variant+ * the `api` list drops `callSubAgent` (and `cancelSubAgent`), and `systemRole` switches to the variant* without the sub-agent section — otherwise the prompt would keep instructing the* model to dispatch a tool that is no longer in its tool list.*/@@ -30,7 +39,7 @@ export const resolveLobeAgentManifest: BuiltinManifestResolver = (context) => {return {...LobeAgentManifest,- api: LobeAgentManifest.api.filter((api) => api.name !== LobeAgentApiName.callSubAgent),+ api: LobeAgentManifest.api.filter((api) => !LOBE_AGENT_SUB_AGENT_APIS.has(api.name)),systemRole: systemPromptWithoutSubAgent,};};diff --git a/packages/builtin-tool-lobe-agent/src/systemRole.ts b/packages/builtin-tool-lobe-agent/src/systemRole.tsindex b91eac4cb7b..0d5898cadb0 100644--- a/packages/builtin-tool-lobe-agent/src/systemRole.ts+++ b/packages/builtin-tool-lobe-agent/src/systemRole.ts@@ -50,6 +50,11 @@ You can dispatch **sub-agents** to handle long-running, multi-step work in isola- If it failed because of the account's budget or quota, do not resend right away; tell the user, and continue the same sub-agent only after they say it is resolved.- A sub-agent can only take one instruction at a time; do not send it a new instruction while it is still running.+**Cancelling or steering a running sub-agent:**+- \`cancelSubAgent({ subAgentId })\` stops a sub-agent that is still running (typically a background one). Use it when its result is no longer needed (the user changed their mind, another result already answered it) or when it is clearly heading the wrong way. No result is delivered for a cancelled sub-agent.+- To steer instead of abandoning it, cancel it and then call \`callSubAgent\` with the same \`subAgentId\` and a corrected instruction; it keeps everything it has done so far.+- Do not cancel a sub-agent just because it is taking a while.+**Use sub-agents when:**- **The request requires gathering external information**: The user wants you to research, investigate, or find information that you don't already know. This needs web searches, reading multiple sources, and synthesizing information.- **The task involves multiple steps**: The request cannot be answered in one simple response - it requires searching, reading, analyzing, and summarizing.diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.tsindex 5f79de5f604..554430199af 100644--- a/packages/builtin-tool-lobe-agent/src/types.ts+++ b/packages/builtin-tool-lobe-agent/src/types.ts@@ -4,6 +4,7 @@ export const LobeAgentApiName = {analyzeMedia: 'analyzeMedia',askUserQuestion: 'askUserQuestion',callSubAgent: 'callSubAgent',+ cancelSubAgent: 'cancelSubAgent',clearTodos: 'clearTodos',createPlan: 'createPlan',createTodos: 'createTodos',@@ -158,6 +159,27 @@ export interface CallSubAgentParams {timeout?: number;}+/**+ * Parameters for cancelSubAgent API+ * Stop a running sub-agent dispatched earlier by callSubAgent.+ */+export interface CancelSubAgentParams {+ /** Why the sub-agent is no longer needed; kept on the tool call for the UI. */+ reason?: string;+ /** Id of the sub-agent to stop (from its `<sub_agent id>` trailer). */+ subAgentId: string;+}++/** State persisted on the cancelSubAgent tool message. */+export interface CancelSubAgentState {+ /**+ * - `cancelled`: the sub-agent was stopped.+ * - `not_running`: it had already finished or stopped; nothing was cancelled.+ */+ status: 'cancelled' | 'not_running';+ threadId: string;+}+/** Execution stats reported back by a finished sub-agent run. */export interface SubAgentRunStats {/** Model the sub-agent ran on */diff --git a/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts b/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.tsindex d8684266d79..a5174723750 100644--- a/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts+++ b/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts@@ -167,4 +167,51 @@ describe('MessageModel background sub-agent calls', () => {expect(await messageModel.claimBackgroundSubAgentDelivery(['b'], 'when-2')).toEqual(['b']);});});++ describe('releaseCancelSuppressedDelivery', () => {+ it('hands back a cancel claim once, so the finished answer is delivered once', async () => {+ await seedCall({ id: 'c', state: { background: true, status: 'pending', threadId: 't' } });+ await messageModel.claimBackgroundSubAgentDelivery(['c'], 'when-cancel', {+ suppressedByCancel: true,+ });+ expect(await readState('c')).toMatchObject({+ cancelSuppressed: true,+ deliveredAt: 'when-cancel',+ });+ // The run still finishes with an answer, recorded as a state merge.+ await messageModel.updateToolMessage('c', { pluginState: { status: 'completed' } });++ expect(await messageModel.releaseCancelSuppressedDelivery(['c'])).toEqual(['c']);+ expect(await readState('c')).toEqual({+ background: true,+ status: 'completed',+ threadId: 't',+ });++ // A real delivery claims it next; a second release must not undo that claim.+ expect(await messageModel.claimBackgroundSubAgentDelivery(['c'], 'when-2')).toEqual(['c']);+ expect(await messageModel.releaseCancelSuppressedDelivery(['c'])).toEqual([]);+ expect(await readState('c')).toMatchObject({ deliveredAt: 'when-2' });+ });++ it('leaves a delivery claim alone', async () => {+ await seedCall({ id: 'd', state: { background: true, status: 'completed' } });+ await messageModel.claimBackgroundSubAgentDelivery(['d'], 'when-1');++ expect(await messageModel.releaseCancelSuppressedDelivery(['d'])).toEqual([]);+ expect(await readState('d')).toMatchObject({ deliveredAt: 'when-1' });+ });++ it('cannot release another user’s row', async () => {+ await seedCall({+ id: 'foreign-cancel',+ ownerId: otherUserId,+ state: { background: true, cancelSuppressed: true, deliveredAt: 'x', status: 'pending' },+ topicId: 'bsa-other-topic',+ });++ expect(await messageModel.releaseCancelSuppressedDelivery(['foreign-cancel'])).toEqual([]);+ expect(await readState('foreign-cancel')).toHaveProperty('deliveredAt', 'x');+ });+ });});diff --git a/packages/database/src/models/message/backgroundSubAgent.ts b/packages/database/src/models/message/backgroundSubAgent.tsindex b9d3ef4a919..a769c196376 100644--- a/packages/database/src/models/message/backgroundSubAgent.ts+++ b/packages/database/src/models/message/backgroundSubAgent.ts@@ -72,17 +72,26 @@ export class MessageBackgroundSubAgentQueries extends MessageScope {* Claim finished background sub-agent results for delivery: stamps* `state.deliveredAt` on the rows that do not carry it yet and returns their* ids. Two deliveries racing for the same row cannot both win it.+ *+ * `cancelSubAgent` claims a still-running call with `suppressedByCancel`, so+ * the run it stops does not wake the parent. The claim also carries+ * `state.cancelSuppressed`, which tells it apart from a real delivery for+ * {@link releaseCancelSuppressedDelivery}.*/claimBackgroundSubAgentDelivery = async (ids: string[],deliveredAt: string,+ options: { suppressedByCancel?: boolean } = {},): Promise<string[]> => {if (ids.length === 0) return [];+ const patch = options.suppressedByCancel+ ? { cancelSuppressed: true, deliveredAt }+ : { deliveredAt };const claimed = await this.db.update(messagePlugins).set({- state: sql`coalesce(${messagePlugins.state}, '{}'::jsonb) || ${JSON.stringify({ deliveredAt })}::jsonb`,+ state: sql`coalesce(${messagePlugins.state}, '{}'::jsonb) || ${JSON.stringify(patch)}::jsonb`,}).where(and(@@ -102,7 +111,31 @@ export class MessageBackgroundSubAgentQueries extends MessageScope {await this.db.update(messagePlugins)- .set({ state: sql`${messagePlugins.state} - 'deliveredAt'` })+ .set({ state: sql`${messagePlugins.state} - 'deliveredAt' - 'cancelSuppressed'` }).where(and(inArray(messagePlugins.id, ids), this.pluginsOwnership()));};++ /**+ * Hand back only the claims `cancelSubAgent` made, and return their ids. A+ * row a real delivery claimed afterwards keeps its claim, so the stopped+ * run's cancel and its completion can both call this without delivering an+ * answer twice.+ */+ releaseCancelSuppressedDelivery = async (ids: string[]): Promise<string[]> => {+ if (ids.length === 0) return [];++ const released = await this.db+ .update(messagePlugins)+ .set({ state: sql`${messagePlugins.state} - 'deliveredAt' - 'cancelSuppressed'` })+ .where(+ and(+ inArray(messagePlugins.id, ids),+ sql`coalesce(jsonb_exists(${messagePlugins.state}, 'cancelSuppressed'), false)`,+ this.pluginsOwnership(),+ ),+ )+ .returning({ id: messagePlugins.id });++ return released.map((row) => row.id);+ };}diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.tsindex bf07b249515..c7d30c47b3b 100644--- a/packages/database/src/models/message/index.ts+++ b/packages/database/src/models/message/index.ts@@ -121,6 +121,7 @@ export class MessageModel {listBackgroundSubAgentCalls: MessageBackgroundSubAgentQueries['listBackgroundSubAgentCalls'];claimBackgroundSubAgentDelivery: MessageBackgroundSubAgentQueries['claimBackgroundSubAgentDelivery'];releaseBackgroundSubAgentDelivery: MessageBackgroundSubAgentQueries['releaseBackgroundSubAgentDelivery'];+ releaseCancelSuppressedDelivery: MessageBackgroundSubAgentQueries['releaseCancelSuppressedDelivery'];private readonly annotations: MessageAnnotationMutations;@@ -213,6 +214,7 @@ export class MessageModel {this.listBackgroundSubAgentCalls = backgroundSubAgents.listBackgroundSubAgentCalls;this.claimBackgroundSubAgentDelivery = backgroundSubAgents.claimBackgroundSubAgentDelivery;this.releaseBackgroundSubAgentDelivery = backgroundSubAgents.releaseBackgroundSubAgentDelivery;+ this.releaseCancelSuppressedDelivery = backgroundSubAgents.releaseCancelSuppressedDelivery;this.getLastMainThreadSpineMessageId = spine.getLastMainThreadSpineMessageId;this.isMessageDescendantOf = spine.isMessageDescendantOf;this.getLatestSpineMessageId = spine.getLatestSpineMessageId;diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex af9974c5dd2..f3db1bb6f50 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -99,6 +99,7 @@ export default {'builtins.lobe-agent.apiName.analyzeMedia.result':'Analyze media: <question>{{question}}</question>','builtins.lobe-agent.apiName.callSubAgent': 'Call sub-agent',+ 'builtins.lobe-agent.apiName.cancelSubAgent': 'Cancel sub-agent','builtins.lobe-agent.subAgent.backgroundHint':'The result will be sent to this conversation when it finishes.','builtins.lobe-agent.subAgent.backgroundRunning': 'Running in background',diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 981fc1db841..25ae41ebfc7 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -745,6 +745,40 @@ export interface ExecSubAgentResult {token?: string;}+/**+ * Parameters for cancelVirtualSubAgent - stop a running `lobe-agent.callSubAgent`+ * child run on behalf of the agent that dispatched it.+ */+export interface CancelVirtualSubAgentParams {+ /** The dispatching agent; the sub-agent's thread must belong to it */+ agentId: string;+ /** The sub-agent's isolation thread id (its `<sub_agent id>`) */+ threadId: string;+ /** The topic the sub-agent was dispatched from */+ topicId: string;+}++/**+ * Result from cancelVirtualSubAgent+ *+ * - `cancelled`: the run was asked to stop and acknowledged it.+ * - `not_running`: there is no live run on the thread; nothing was stopped.+ * - `failed`: the thread is not a cancellable sub-agent, or the stop could not+ * be confirmed (`error` says which).+ */+export interface CancelVirtualSubAgentResult {+ error?: string;+ /** The stopped (or last) run of the sub-agent */+ operationId?: string;+ status: 'cancelled' | 'failed' | 'not_running';+ /**+ * For `cancelled`: whether the run already reached its end. `false` means it+ * is still finishing its current step and refuses follow-ups until then.+ */+ stopped?: boolean;+ threadId: string;+}+/*** @deprecated Use ExecSubAgentParams instead*/