🤯 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(sub-agent): steer a running sub-agent instead of refusing the follow-up (#22377)
Lobehub Coder6444fde0e864
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentBackground.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentBackground.test.tsindex cc03b97bd17..f0293eb2e20 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentBackground.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentBackground.test.ts@@ -100,6 +100,38 @@ describe('buildServerVirtualSubAgentRunner in background mode', () => {expect(result).toMatchObject({ started: true, threadId: 'thread-1' });});+ // Steering a running sub-agent starts no run: this call's row only holds the+ // receipt, and must not count as a background run still waiting for its result.+ it('settles the placeholder of an instruction that steered a running sub-agent', async () => {+ const { messageModel, runner } = buildRunner({+ operationId: 'running-child-op',+ steered: true,+ success: true,+ threadId: 'thread-1',+ });++ const result = await runner.run({+ background: true,+ description: 'research',+ instruction: 'only 2025',+ subAgentId: 'thread-1',+ });++ expect(messageModel.updatePluginState).toHaveBeenCalledWith('placeholder-1', {+ background: false,+ status: 'completed',+ steered: true,+ threadId: 'thread-1',+ });+ expect(result).toEqual({+ started: true,+ steered: true,+ subOperationId: 'running-child-op',+ threadId: 'thread-1',+ toolMessageId: 'placeholder-1',+ });+ });+it('leaves a foreground placeholder as before', async () => {const { messageModel, runner } = buildRunner();diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 33b1cdf229d..8c26fd325d9 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -369,7 +369,14 @@ export const buildServerVirtualSubAgentRunner = (title: description,topicId,})) as- { error?: string; operationId?: string; success?: boolean; threadId?: string } | undefined;+ | {+ error?: string;+ operationId?: string;+ steered?: boolean;+ success?: boolean;+ threadId?: string;+ }+ | undefined;// 3. If the child op never started, no completion bridge will fire — parking// the parent on it would hang forever. Drop the placeholder and signal@@ -405,6 +412,34 @@ export const buildServerVirtualSubAgentRunner = (};}+ // The instruction steered the still-running sub-agent: this call's row+ // only holds the receipt. It must not read as a running background call+ // (those count against the limit and wait for delivery) — the running+ // call's own row reports the result.+ if (result.steered) {+ await ctx.messageModel+ .updatePluginState(placeholder.id, {+ background: false,+ status: 'completed',+ steered: true,+ threadId: result.threadId,+ })+ .catch((error: unknown) =>+ log(+ 'buildServerVirtualSubAgentRunner: failed to settle steer receipt %s: %O',+ placeholder.id,+ error,+ ),+ );+ return {+ started: true,+ steered: true,+ subOperationId: result.operationId,+ threadId: result.threadId ?? '',+ toolMessageId: placeholder.id,+ };+ }+// A background parent never parks, so its card has no other way to link// the running thread. Only `threadId` is patched: the merge leaves the// `status` key to the completion bridge, which may already have written it.diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex eb956664ada..bf321a87aa0 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -206,6 +206,12 @@ export const RedisKeys = {* Full key: agentSteer:hetero_deliveries:v1:{operationId}*/heteroDeliveries: (operationId: string): string => `hetero_deliveries:v1:${operationId}`,+ /**+ * Marks a sub-agent run whose final queue read came back empty: it ends+ * without reading again, so a steer appended behind it must be taken back.+ * Full key: agentSteer:sealed_run:v1:{operationId}+ */+ sealedRun: (operationId: string): string => `sealed_run:v1:${operationId}`,},/*** Agent identity scope — see {@link RedisKeyNamespace.AGENT_IDENTITY}.diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/graphSteerReopen.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/graphSteerReopen.test.tsnew file mode 100644index 00000000000..7fab6ed1885--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/graphSteerReopen.test.ts@@ -0,0 +1,95 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { withGraphSteerReopen } from '../graphSteerReopen';++const { steerQueueUnseal } = vi.hoisted(() => ({ steerQueueUnseal: vi.fn() }));++vi.mock('@/server/services/redis', () => ({+ redisService: { steerQueue: { unseal: steerQueueUnseal } },+}));++const subAgentOrigin = {+ agentId: 'agt-1',+ lineage: { isSubAgent: true, parentOperationId: 'op-parent' },+ threadId: 'thd-sub',+ topicId: 'tpc-1',+};++const stateOf = (phase?: 'node_in' | 'node_out' | 'fin', origin: unknown = subAgentOrigin) =>+ ({+ metadata: phase+ ? {+ __graphRuntimeState: {+ graphContext: { edgeTraversalCounts: {}, store: {} },+ graphState:+ phase === 'fin'+ ? { phase, reason: 'completed' }+ : { active: true, attempts: 1, currentNode: 'work', phase },+ instructionCount: 3,+ terminalNode: 'verify',+ },+ }+ : undefined,+ origin,+ }) as unknown as AgentState;++const instruction = { payload: {}, type: 'call_llm' } as any;+const context = { phase: 'llm_result' } as any;++describe('withGraphSteerReopen', () => {+ const callLlm = vi.fn();+ const callTool = vi.fn();++ beforeEach(() => {+ vi.clearAllMocks();+ callLlm.mockResolvedValue({ events: [], newState: {} });+ steerQueueUnseal.mockResolvedValue(undefined);+ });++ it('reopens the queue before a graph sub-agent starts another node’s work', async () => {+ const order: string[] = [];+ steerQueueUnseal.mockImplementation(async () => order.push('unseal'));+ callLlm.mockImplementation(async () => {+ order.push('call_llm');+ return { events: [], newState: {} };+ });+ const executors = withGraphSteerReopen({ call_llm: callLlm }, 'op-child');++ await executors.call_llm!(instruction, stateOf('node_in'), context);++ expect(steerQueueUnseal).toHaveBeenCalledWith('op-child');+ expect(order).toEqual(['unseal', 'call_llm']);+ });++ it.each([+ ['a node’s output extraction', stateOf('node_out')],+ ['a run no graph drives', stateOf()],+ ['a top-level graph run', stateOf('node_in', { agentId: 'agt-1', topicId: 'tpc-1' })],+ ])('leaves the seal alone for %s', async (_case, state) => {+ const executors = withGraphSteerReopen({ call_llm: callLlm }, 'op-child');++ await executors.call_llm!(instruction, state, context);++ expect(steerQueueUnseal).not.toHaveBeenCalled();+ expect(callLlm).toHaveBeenCalledWith(instruction, state, context);+ });++ it('still makes the LLM call when reopening fails', async () => {+ steerQueueUnseal.mockRejectedValue(new Error('redis down'));+ const executors = withGraphSteerReopen({ call_llm: callLlm }, 'op-child');++ await expect(executors.call_llm!(instruction, stateOf('node_in'), context)).resolves.toEqual({+ events: [],+ newState: {},+ });+ expect(callLlm).toHaveBeenCalledTimes(1);+ });++ it('leaves the other executors as they are', () => {+ const executors = withGraphSteerReopen({ call_llm: callLlm, call_tool: callTool }, 'op');++ expect(executors.call_tool).toBe(callTool);+ expect(withGraphSteerReopen({ call_tool: callTool }, 'op')).toEqual({ call_tool: callTool });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/runtimeFactory.graphSteerReopen.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/runtimeFactory.graphSteerReopen.test.tsnew file mode 100644index 00000000000..c91770200af--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/runtimeFactory.graphSteerReopen.test.ts@@ -0,0 +1,35 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import type { RuntimeFactoryDeps } from '../runtimeFactory';+import { createAgentRuntime } from '../runtimeFactory';++const reopen = vi.hoisted(() => ({+ withGraphSteerReopen: vi.fn((executors: unknown) => executors),+}));+vi.mock('../graphSteerReopen', () => reopen);+vi.mock('@/database/models/agentInbox', () => ({ AgentInboxModel: { isInboxTopic: vi.fn() } }));++describe('createAgentRuntime — graph steer reopen', () => {+ it('runs the operation’s LLM calls through the graph steer reopen', async () => {+ const deps = {+ agentFactory: vi.fn((config: any) => ({ config, runner: vi.fn() })),+ completeGroupMemberBarrier: vi.fn(),+ coordinator: { isInterrupted: vi.fn(), loadAgentState: vi.fn() },+ delegate: {},+ serverDB: {},+ userId: 'user_1',+ } as unknown as RuntimeFactoryDeps;++ await createAgentRuntime(deps, {+ agentState: { origin: { topicId: 'tpc_1', userId: 'user_1' } },+ operationId: 'op_1',+ stepIndex: 0,+ });++ expect(reopen.withGraphSteerReopen).toHaveBeenCalledWith(+ expect.objectContaining({ call_llm: expect.any(Function) }),+ 'op_1',+ );+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.tsindex 28646cf119b..45bb3196c72 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts@@ -6,11 +6,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { finishOperation } from '../executeStep/completion';import { prepareStepInput } from '../executeStep/prepare';-import { readQueuedMessagesFlag } from '../operationControl';+import { injectQueuedFollowUp, readQueuedMessagesFlag } from '../operationControl';-const { steerQueueLength } = vi.hoisted(() => ({ steerQueueLength: vi.fn() }));+const { steerQueueLength, steerQueueSeal, steerQueueUnseal } = vi.hoisted(() => ({+ steerQueueLength: vi.fn(),+ steerQueueSeal: vi.fn(),+ steerQueueUnseal: vi.fn(),+}));vi.mock('@/server/services/redis', () => ({- redisService: { steerQueue: { length: steerQueueLength } },+ redisService: {+ steerQueue: { length: steerQueueLength, seal: steerQueueSeal, unseal: steerQueueUnseal },+ },}));const stateOf = (overrides: Partial<AgentState> = {}) =>@@ -25,6 +31,8 @@ describe('server-side steer queue in the step loop', () => {beforeEach(() => {vi.clearAllMocks();steerQueueLength.mockResolvedValue(0);+ steerQueueSeal.mockResolvedValue(undefined);+ steerQueueUnseal.mockResolvedValue(undefined);});describe('readQueuedMessagesFlag', () => {@@ -79,6 +87,105 @@ describe('server-side steer queue in the step loop', () => {});});+ describe('injectQueuedFollowUp — a running sub-agent’s steer queue', () => {+ const createDeps = (injected?: { messageId: string }) =>+ ({+ delegate: { injectQueuedFollowUp: vi.fn().mockResolvedValue(injected) },+ userId: 'user-1',+ }) as any;+ const child = stateOf({+ origin: {+ agentId: 'agt-1',+ lineage: { isSubAgent: true, parentOperationId: 'op-parent' },+ threadId: 'thd-sub',+ topicId: 'tpc-1',+ },+ status: 'running',+ });++ it('takes the parent’s queued instruction from the sub-agent’s thread queue', async () => {+ steerQueueLength.mockResolvedValue(1);+ const deps = createDeps({ messageId: 'msg-steer' });++ await expect(injectQueuedFollowUp(deps, 'op-child', 2, child)).resolves.toEqual({+ messageId: 'msg-steer',+ });+ const scope = { threadId: 'thd-sub', topicId: 'tpc-1', userId: 'user-1' };+ expect(steerQueueLength).toHaveBeenCalledWith(scope, 'op-child');+ expect(deps.delegate.injectQueuedFollowUp).toHaveBeenCalledWith({+ operationId: 'op-child',+ scope,+ state: child,+ });+ });++ it('skips the join when nothing waits for the sub-agent', async () => {+ const deps = createDeps({ messageId: 'msg-steer' });++ await expect(injectQueuedFollowUp(deps, 'op-child', 2, child)).resolves.toBeUndefined();+ expect(deps.delegate.injectQueuedFollowUp).not.toHaveBeenCalled();+ });++ it('seals the sub-agent before its last read, so a later steer is taken back', async () => {+ const deps = createDeps({ messageId: 'msg-steer' });++ await expect(+ injectQueuedFollowUp(deps, 'op-child', 2, child, { lastRead: true }),+ ).resolves.toBeUndefined();+ expect(steerQueueSeal).toHaveBeenCalledWith('op-child');+ expect(steerQueueSeal.mock.invocationCallOrder[0]).toBeLessThan(+ steerQueueLength.mock.invocationCallOrder[0],+ );+ expect(steerQueueUnseal).not.toHaveBeenCalled();+ });++ it('unseals when the last read took a steer in, since the sub-agent answers again', async () => {+ steerQueueLength.mockResolvedValue(1);+ const deps = createDeps({ messageId: 'msg-steer' });++ await expect(+ injectQueuedFollowUp(deps, 'op-child', 2, child, { lastRead: true }),+ ).resolves.toEqual({ messageId: 'msg-steer' });+ expect(steerQueueUnseal).toHaveBeenCalledWith('op-child');+ });++ it('keeps the joined steer when unsealing fails', async () => {+ steerQueueLength.mockResolvedValue(1);+ steerQueueUnseal.mockRejectedValue(new Error('redis down'));+ const deps = createDeps({ messageId: 'msg-steer' });++ await expect(+ injectQueuedFollowUp(deps, 'op-child', 2, child, { lastRead: true }),+ ).resolves.toEqual({ messageId: 'msg-steer' });+ });++ it('retries a seal that Redis rejects before reading', async () => {+ steerQueueSeal.mockRejectedValueOnce(new Error('timeout')).mockResolvedValueOnce(undefined);++ await injectQueuedFollowUp(createDeps(), 'op-child', 2, child, { lastRead: true });++ expect(steerQueueSeal).toHaveBeenCalledTimes(2);+ expect(steerQueueSeal.mock.invocationCallOrder[1]).toBeLessThan(+ steerQueueLength.mock.invocationCallOrder[0],+ );+ });++ it('does not seal on a read the run makes before another LLM call', async () => {+ await injectQueuedFollowUp(createDeps(), 'op-child', 2, child);++ expect(steerQueueSeal).not.toHaveBeenCalled();+ });++ it('has no queue for a child run outside a thread', async () => {+ steerQueueLength.mockResolvedValue(1);+ const deps = createDeps({ messageId: 'msg-steer' });+ const noThread = stateOf({ origin: { lineage: { isSubAgent: true }, topicId: 'tpc-1' } });++ await expect(injectQueuedFollowUp(deps, 'op-child', 2, noThread)).resolves.toBeUndefined();+ expect(steerQueueLength).not.toHaveBeenCalled();+ });+ });+describe('finishOperation', () => {const createDeps = (startQueuedFollowUp = vi.fn().mockResolvedValue(undefined)) => {const order: string[] = [];@@ -189,7 +296,9 @@ describe('server-side steer queue in the step loop', () => {const { currentContext, currentState } = await prepare(deps, phase);- expect(deps.injectQueuedFollowUp).toHaveBeenCalledWith('op-1', 2, expect.anything());+ expect(deps.injectQueuedFollowUp).toHaveBeenCalledWith('op-1', 2, expect.anything(), {+ lastRead: false,+ });expect(currentContext).toMatchObject({payload: { parentMessageId: 'msg-steer' },phase: 'user_input',@@ -216,6 +325,143 @@ describe('server-side steer queue in the step loop', () => {expect(deps.injectQueuedFollowUp).not.toHaveBeenCalled();});+ describe('a running sub-agent steered by its parent', () => {+ const subAgentOrigin = {+ agentId: 'agt-1',+ lineage: { isSubAgent: true, parentOperationId: 'op-parent' },+ threadId: 'thd-sub',+ topicId: 'tpc-1',+ };+ const prepareChild = (deps: any, phase: string, payload: Record<string, unknown>) =>+ prepareStepInput(deps, {+ agentState: stateOf({+ messages: toolMessages,+ origin: subAgentOrigin,+ status: 'running',+ } as any),+ params: {+ context: { payload: { parentMessageId: 'msg-tool', ...payload }, phase },+ operationId: 'op-child',+ stepIndex: 4,+ } as any,+ stepEntryMessages: undefined as any,+ });++ it('injects the steer instruction into the sub-agent context on its next step', async () => {+ const deps = createDeps({ messageId: 'msg-steer' });++ const { currentContext, currentState } = await prepareChild(deps, 'tool_result', {});++ expect(deps.injectQueuedFollowUp).toHaveBeenCalledWith('op-child', 4, expect.anything(), {+ lastRead: false,+ });+ // The next LLM call runs on the steer message, read back from the thread.+ expect(currentContext).toMatchObject({+ payload: { parentMessageId: 'msg-steer' },+ phase: 'user_input',+ });+ expect(currentState.messages).toEqual(refreshed);+ });++ const prepareGraphChild = (+ deps: any,+ currentNode: string,+ terminalNode?: string,+ phase: 'node_in' | 'node_out' = 'node_in',+ ) =>+ prepareStepInput(deps, {+ agentState: stateOf({+ messages: toolMessages,+ metadata: {+ __graphRuntimeState: {+ graphContext: { edgeTraversalCounts: {}, store: {} },+ graphState: { active: true, attempts: 1, currentNode, phase },+ instructionCount: 2,+ terminalNode,+ },+ },+ origin: subAgentOrigin,+ status: 'running',+ } as any),+ params: {+ context: {+ payload: { hasToolsCalling: false, result: { content: 'node', tool_calls: [] } },+ phase: 'llm_result',+ },+ operationId: 'op-child',+ stepIndex: 4,+ } as any,+ stepEntryMessages: undefined as any,+ });++ it.each([+ ['an intermediate node', 'draft', 'review'],+ ['a state without its terminal node', 'review', undefined],+ ])('takes the steer at a graph’s result at %s without sealing', async (_case, node, end) => {+ const deps = createDeps({ messageId: 'msg-steer' });++ const { currentContext } = await prepareGraphChild(deps, node, end);++ // Read before the graph moves on, so later nodes work with the+ // correction; not the run's last read, so the queue stays open.+ expect(deps.injectQueuedFollowUp).toHaveBeenCalledWith('op-child', 4, expect.anything(), {+ lastRead: false,+ });+ expect(currentContext).toMatchObject({+ payload: { parentMessageId: 'msg-steer' },+ phase: 'user_input',+ });+ });++ it.each([+ ['an intermediate node', 'draft'],+ ['the terminal node', 'review'],+ ])('leaves a graph’s output extraction at %s alone', async (_case, node) => {+ const deps = createDeps({ messageId: 'msg-steer' });++ const { currentContext } = await prepareGraphChild(deps, node, 'review', 'node_out');++ // The graph takes the extraction reply only as an llm_result; the+ // node's own answer before it was the read.+ expect(deps.injectQueuedFollowUp).not.toHaveBeenCalled();+ expect(currentContext).toMatchObject({ phase: 'llm_result' });+ });++ it('makes its last read at the graph’s terminal node', async () => {+ const deps = createDeps(undefined);++ await prepareGraphChild(deps, 'review', 'review');++ expect(deps.injectQueuedFollowUp).toHaveBeenCalledWith('op-child', 4, expect.anything(), {+ lastRead: true,+ });+ });++ it('takes the steer at its final answer instead of finishing without it', async () => {+ const deps = createDeps({ messageId: 'msg-steer' });++ const { currentContext } = await prepareChild(deps, 'llm_result', {+ hasToolsCalling: false,+ result: { content: 'done', tool_calls: [] },+ });++ // Its last read before it ends: sealed, so a steer that misses it is taken back.+ expect(deps.injectQueuedFollowUp).toHaveBeenCalledWith('op-child', 4, expect.anything(), {+ lastRead: true,+ });+ expect(currentContext).toMatchObject({ phase: 'user_input' });+ });++ it('runs the tools the model asked for before taking the steer', async () => {+ const deps = createDeps({ messageId: 'msg-steer' });++ await prepareChild(deps, 'llm_result', { hasToolsCalling: true, toolsCalling: [{}] });+ await prepareChild(deps, 'llm_result', { result: { tool_calls: [{ id: 'call-2' }] } });++ expect(deps.injectQueuedFollowUp).not.toHaveBeenCalled();+ });+ });+it('lets the agent park for a tool still waiting for approval first', async () => {const deps = createDeps({ messageId: 'msg-steer' });const pending = [diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.tsindex 3bdc4c69066..29d4696cb66 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts@@ -3,6 +3,8 @@ import {type AgentRuntimeContext,type AgentState,findCurrentTurnPendingToolMessages,+ isGraphAgentIntermediateResult,+ isGraphAgentOutputExtraction,} from '@lobechat/agent-runtime';import { type ChatToolPayload } from '@lobechat/types';import debug from 'debug';@@ -28,6 +30,24 @@ const LLM_NEXT_PHASES = new Set(['sub_agents_batch_result',]);+/**+ * A sub-agent's answer: the model replied without asking for a tool, so no+ * tool result follows it to read a steer at. A top-level run hands a follow-up+ * that missed its last decision point to the next turn; a sub-agent has no+ * next turn for its parent's steer instruction, so the instruction joins here+ * instead and the sub-agent answers again with it in context.+ */+const isSubAgentAnswer = (context: AgentRuntimeContext, state: AgentState): boolean => {+ if (!state.origin?.lineage?.isSubAgent || context.phase !== 'llm_result') return false;+ // A graph node's output extraction is no answer: the graph needs that reply+ // back as an `llm_result`, and the node's own answer before it was the read.+ if (isGraphAgentOutputExtraction(state)) return false;+ const payload = context.payload as+ { hasToolsCalling?: boolean; result?: { tool_calls?: unknown[] } } | undefined;++ return !payload?.hasToolsCalling && !payload?.result?.tool_calls?.length;+};+/** What this module reads off the service. */export type StepPrepareDeps = Pick<AgentRuntimeServiceContext,@@ -252,14 +272,23 @@ export async function prepareStepInput(// the whole run. Re-entered like an async-tool resume: messages refreshed// from the DB (which now hold the steer message) and a `user_input` phase// anchored on it. Not while a tool of this turn still waits for approval —- // the agent has to park for that first.+ // the agent has to park for that first. A sub-agent also takes its parent's+ // steer instruction at an answer (see `isSubAgentAnswer`). A graph routes a+ // node's answer before its terminal node on to the next node, so a steer+ // joins there too — the node answers again with it, and later nodes work+ // with the correction — but only the terminal node's answer is the run's+ // last read.+ const subAgentAnswer = !!currentContext && isSubAgentAnswer(currentContext, currentState);+ const subAgentFinalAnswer = subAgentAnswer && !isGraphAgentIntermediateResult(currentState);if (currentContext &&!forcedFinishState &&- LLM_NEXT_PHASES.has(currentContext.phase) &&+ (LLM_NEXT_PHASES.has(currentContext.phase) || subAgentAnswer) &&findCurrentTurnPendingToolMessages(currentState.messages).length === 0) {- const injected = await deps.injectQueuedFollowUp(operationId, stepIndex, currentState);+ const injected = await deps.injectQueuedFollowUp(operationId, stepIndex, currentState, {+ lastRead: subAgentFinalAnswer,+ });if (injected) {currentState = structuredClone(currentState);currentState.messages = await deps.refreshMessagesFromDB(currentState);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/graphSteerReopen.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/graphSteerReopen.tsnew file mode 100644index 00000000000..b0aa6c0f3ef--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/graphSteerReopen.ts@@ -0,0 +1,45 @@+import type { AgentInstruction, InstructionExecutor } from '@lobechat/agent-runtime';+import { isGraphAgentNodeWork } from '@lobechat/agent-runtime';+import debug from 'debug';++import { redisService } from '@/server/services/redis';++const log = debug('lobe-server:steer-queue');++type RuntimeExecutors = Partial<Record<AgentInstruction['type'], InstructionExecutor>>;++/**+ * Reopen a graph sub-agent's steer queue when its graph moves on to another+ * node's work.+ *+ * A sub-agent seals its queue at its terminal node's answer, its last read+ * before it ends (`injectQueuedFollowUp`). A graph whose terminal node routes+ * back to another node (a review sending the work back) does not end there:+ * it starts that node's LLM call in the same step. Clearing the seal right+ * before that call lets the parent steer it again; the call ends in a tool+ * result or an answer, where the queue is read once more.+ *+ * Best-effort: a seal left in place only makes the parent wait for the result.+ */+export const withGraphSteerReopen = (+ executors: RuntimeExecutors,+ operationId: string,+): RuntimeExecutors => {+ const callLlm = executors.call_llm;+ if (!callLlm) return executors;++ return {+ ...executors,+ call_llm: async (instruction, state, context) => {+ if (state.origin?.lineage?.isSubAgent && isGraphAgentNodeWork(state)) {+ await redisService.steerQueue+ .unseal(operationId)+ .catch((error) =>+ log('[%s] Reopening the steer queue for a graph node failed: %O', operationId, error),+ );+ }++ return callLlm(instruction, state, context);+ },+ };+};diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.tsindex 50b35fd9491..6a4ec2ce473 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts@@ -10,7 +10,7 @@ import {type DeferredToolResultControlInput,loadDurableToolResultHooks,} from '../hooks/deferredToolResultControl';-import { steerQueueScopeOf } from '../steerQueueScope';+import { steerQueueScopeOf, subAgentSteerQueueScopeOf } from '../steerQueueScope';import {type AgentStepContinuation,type OperationStatusResult,@@ -290,6 +290,35 @@ export async function readQueuedMessagesFlag(}}+const SEAL_ATTEMPTS = 3;+const SEAL_RETRY_DELAY_MS = 200;++/**+ * Seal the run before its last queue read, retrying a transient Redis error:+ * an unsealed last read lets a steer appended after it wait behind a run that+ * will not read again. Redis down for every attempt also fails the parent's+ * append, so the run then ends without the seal rather than hanging on it.+ */+const sealForLastRead = async (operationId: string, stepIndex: number) => {+ for (let attempt = 1; attempt <= SEAL_ATTEMPTS; attempt++) {+ try {+ await redisService.steerQueue.seal(operationId);+ return;+ } catch (error) {+ log(+ '[%s][%d] Sealing the steer queue failed (%d): %O',+ operationId,+ stepIndex,+ attempt,+ error,+ );+ if (attempt < SEAL_ATTEMPTS) {+ await new Promise((resolve) => setTimeout(resolve, SEAL_RETRY_DELAY_MS * attempt));+ }+ }+ }+};+/*** Join the follow-ups queued behind this run into it, right before its next* LLM call, instead of ending the run and starting another for them. Hands off@@ -307,14 +336,34 @@ export async function injectQueuedFollowUp(operationId: string,stepIndex: number,state: AgentState,+ options?: { lastRead?: boolean },): Promise<{ messageId: string } | undefined> {- const scope = steerQueueScopeOf(state, deps.userId);+ // A sub-agent has no composer of its own; its queue holds the steer+ // instructions its parent sent while it was running.+ const topLevelScope = steerQueueScopeOf(state, deps.userId);+ const scope = topLevelScope ?? subAgentSteerQueueScopeOf(state, deps.userId);if (!scope || !deps.delegate.injectQueuedFollowUp) return;+ // A sub-agent ending after this read has no hand-back to catch a steer its+ // parent appends meanwhile. Sealed before the read, the run makes that+ // parent take the steer back (`queueSubAgentSteer`) instead of leaving it+ // queued behind a run that will not read again.+ const sealing = !!options?.lastRead && !topLevelScope;+ if (sealing) await sealForLastRead(operationId, stepIndex);+try {if ((await redisService.steerQueue.length(scope, operationId)) === 0) return;const injected = await deps.delegate.injectQueuedFollowUp({ operationId, scope, state });+ // It answers again with the steer in context, so it reads its queue again.+ // A seal left in place only makes the parent wait for the result instead.+ if (injected && sealing) {+ await redisService.steerQueue+ .unseal(operationId)+ .catch((error) =>+ log('[%s][%d] Unsealing the steer queue failed: %O', operationId, stepIndex, error),+ );+ }if (injected) {log('[%s][%d] Joined queued follow-ups into the run as %s',diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.tsindex ce29d978a6a..8bc9bc0b719 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts@@ -24,6 +24,7 @@ import { hookDispatcher } from '../hooks';import { createEvalConnectorHook } from './evalConnectorHook';import { createEvalToolGateHook } from './evalToolGateHook';import { DurableStatusUnavailableError } from './executionErrors';+import { withGraphSteerReopen } from './graphSteerReopen';import type { AgentRuntimeServiceContext } from './types';const log = debug('lobe-server:agent-runtime-service');@@ -307,7 +308,7 @@ export async function createAgentRuntime(// Create Agent Runtime instanceconst runtime = new AgentRuntime(agent as any, {- executors: createRuntimeExecutors(executorContext),+ executors: withGraphSteerReopen(createRuntimeExecutors(executorContext), operationId),});return { agent, runtime };diff --git a/apps/server/src/services/agentRuntime/steerQueueScope.ts b/apps/server/src/services/agentRuntime/steerQueueScope.tsindex fdd9cf52a43..fb211936750 100644--- a/apps/server/src/services/agentRuntime/steerQueueScope.ts+++ b/apps/server/src/services/agentRuntime/steerQueueScope.ts@@ -17,3 +17,19 @@ export const steerQueueScopeOf = (return { threadId: origin.threadId ?? null, topicId: origin.topicId, userId };};++/**+ * The queue a running `callSubAgent` child reads steer instructions from: its+ * isolation thread on the parent's topic. The parent agent fills it when it+ * sends the child another instruction mid-run (`callSubAgent({ subAgentId })`);+ * nobody else types behind a child run. `undefined` for a top-level run.+ */+export const subAgentSteerQueueScopeOf = (+ state: AgentState,+ userId: string,+): SteerQueueScope | undefined => {+ const origin = state.origin;+ if (!origin?.topicId || !origin.threadId || !origin.lineage?.isSubAgent) return;++ return { threadId: origin.threadId, topicId: origin.topicId, userId };+};diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.tsindex 4fbf30a02b5..9febc0719b1 100644--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts@@ -2,6 +2,8 @@ import type { ExecAgentResult, ExecSubAgentParams } from '@lobechat/types';import { ThreadStatus, ThreadType } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { hookDispatcher } from '@/server/services/agentRuntime/hooks';+import { AiAgentService } from '../index';// Mock trusted client to avoid server-side env access@@ -22,6 +24,11 @@ const mockThreadModel = {const mockOperationFindById = vi.fn();const mockFindMessagePlugin = vi.fn();+const mockQueueSubAgentSteer = vi.fn();++vi.mock('../steerQueue/subAgent', () => ({+ queueSubAgentSteer: (...args: unknown[]) => mockQueueSubAgentSteer(...args),+}));vi.mock('@/database/models/thread', () => ({ThreadModel: vi.fn().mockImplementation(function () {@@ -576,16 +583,179 @@ describe('AiAgentService.execSubAgent', () => {});});+ describe('while its previous run is still going', () => {+ beforeEach(() => {+ mockThreadModel.findById.mockResolvedValue({+ agentId: 'agent-1',+ id: 'thread-old',+ metadata: { operationId: 'op-old' },+ sourceMessageId: 'tool-msg-1',+ status: ThreadStatus.Processing,+ topicId: 'topic-1',+ type: ThreadType.Isolation,+ });+ mockOperationFindById.mockImplementation(async (id: string) =>+ id === 'op-old' ? { status: 'running' } : { trigger: 'cli' },+ );+ mockQueueSubAgentSteer.mockResolvedValue({ queued: true });+ });++ it('queues the instruction for the running sub-agent instead of refusing it', async () => {+ const execAgentSpy = vi.spyOn(service, 'execAgent');++ const result = await service.execVirtualSubAgent(followUp);++ expect(mockQueueSubAgentSteer).toHaveBeenCalledWith(+ { db: mockDb, userId, workspaceId: undefined },+ {+ agentId: 'agent-1',+ groupId: undefined,+ instruction: 'Hand over what you found so far',+ operationId: 'op-old',+ threadId: 'thread-old',+ topicId: 'topic-1',+ },+ );+ // No second run on the thread: the running one takes the instruction.+ expect(mockThreadModel.claimForRun).not.toHaveBeenCalled();+ expect(execAgentSpy).not.toHaveBeenCalled();+ expect(result).toEqual({+ assistantMessageId: '',+ operationId: 'op-old',+ steered: true,+ success: true,+ threadId: 'thread-old',+ });+ });++ it('refuses an instruction for a sub-agent another member’s turn is running', async () => {+ mockOperationFindById.mockImplementation(async (id: string) =>+ id === 'op-old' ? { status: 'running', userId: 'another-member' } : { trigger: 'cli' },+ );+ const execAgentSpy = vi.spyOn(service, 'execAgent');++ const result = await service.execVirtualSubAgent(followUp);++ // It reads its queue as that member, so a steer from this turn would never arrive.+ expect(mockQueueSubAgentSteer).not.toHaveBeenCalled();+ expect(mockThreadModel.claimForRun).not.toHaveBeenCalled();+ expect(execAgentSpy).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.error).toContain('is running for another member');+ });++ it('steers a sub-agent its own member’s earlier turn is running', async () => {+ mockOperationFindById.mockImplementation(async (id: string) =>+ id === 'op-old' ? { status: 'running', userId } : { trigger: 'cli' },+ );++ const result = await service.execVirtualSubAgent(followUp);++ expect(mockQueueSubAgentSteer).toHaveBeenCalled();+ expect(result).toMatchObject({ steered: true, success: true });+ });++ it('starts a new run when the sub-agent finished while the instruction was queued', async () => {+ mockQueueSubAgentSteer.mockResolvedValue({ queued: false, reason: 'ended' });+ let reads = 0;+ mockOperationFindById.mockImplementation(async (id: string) => {+ if (id !== 'op-old') return { trigger: 'cli' };+ reads += 1;+ return { status: reads === 1 ? 'running' : 'done' };+ });+ const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue(execAgentResult);++ const result = await service.execVirtualSubAgent(followUp);++ expect(mockThreadModel.claimForRun).toHaveBeenCalled();+ expect(execAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({ prompt: 'Hand over what you found so far' }),+ );+ expect(result).toMatchObject({ operationId: 'op-new', success: true });+ expect(result.steered).toBeUndefined();+ });++ it('steers the run that won the thread when another follow-up claimed it first', async () => {+ mockThreadModel.findById.mockResolvedValueOnce({+ agentId: 'agent-1',+ id: 'thread-old',+ metadata: { operationId: 'op-done' },+ sourceMessageId: 'tool-msg-1',+ status: ThreadStatus.Completed,+ topicId: 'topic-1',+ type: ThreadType.Isolation,+ });+ mockOperationFindById.mockImplementation(async (id: string) =>+ id === 'op-done' ? { status: 'done' } : { status: 'running' },+ );+ mockThreadModel.claimForRun.mockResolvedValue(false);++ const result = await service.execVirtualSubAgent(followUp);++ expect(mockQueueSubAgentSteer).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ operationId: 'op-old' }),+ );+ expect(result).toMatchObject({ steered: true, success: true });+ });++ it('closes the call-agent hook pair for a steer', async () => {+ const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);++ await service.execVirtualSubAgent(followUp);++ const events = dispatch.mock.calls.map(([, event]) => event);+ expect(events).toEqual(['beforeCallAgent', 'afterCallAgent']);+ expect(dispatch).toHaveBeenLastCalledWith(+ 'parent-op-2',+ 'afterCallAgent',+ expect.objectContaining({+ subOperationId: 'op-old',+ success: true,+ threadId: 'thread-old',+ }),+ );+ dispatch.mockRestore();+ });++ it('tells the parent not to resend when the steer may already be queued', async () => {+ mockQueueSubAgentSteer.mockResolvedValue({ queued: false, reason: 'unknown' });++ const result = await service.execVirtualSubAgent(followUp);++ expect(result.success).toBe(false);+ expect(result.error).toContain('Do not send it again yet');+ });++ it('explains a full queue to the parent', async () => {+ mockQueueSubAgentSteer.mockResolvedValue({ queued: false, reason: 'full' });++ const result = await service.execVirtualSubAgent(followUp);++ expect(result.success).toBe(false);+ expect(result.error).toContain('too many instructions waiting');+ });+ });+it.each([[- 'its previous run is still going',- () => mockOperationFindById.mockResolvedValue({ status: 'running' }),- 'still running',+ 'another follow-up keeps winning the thread',+ () => mockThreadModel.claimForRun.mockResolvedValue(false),+ 'busy with another instruction',],[- 'another follow-up claimed it first',- () => mockThreadModel.claimForRun.mockResolvedValue(false),- 'still running',+ 'its run has not recorded an operation yet',+ () =>+ mockThreadModel.findById.mockResolvedValue({+ agentId: 'agent-1',+ id: 'thread-old',+ metadata: {},+ sourceMessageId: 'tool-msg-1',+ status: ThreadStatus.Processing,+ topicId: 'topic-1',+ type: ThreadType.Isolation,+ }),+ 'still starting',],['it belongs to another topic',diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex cf2ab82db38..3f98dbff69a 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -87,6 +87,7 @@ import { resolveAgentSenderFromOperation } from './sourceAttribution';import { startQueuedFollowUp } from './steerQueue';import { injectQueuedFollowUp } from './steerQueue/inject';import { findOwnLiveRuns } from './steerQueue/liveRuns';+import { queueSubAgentSteer } from './steerQueue/subAgent';import type { SubAgentLlmRelayRequest } from './subAgentLlmRelay';import { closeSubAgentLlmRelay, openSubAgentLlmRelay } from './subAgentLlmRelay';import type { SubAgentRunDeps } from './subAgentRuns';@@ -227,6 +228,8 @@ export class AiAgentService {agentRuntimeService: this.agentRuntimeService,execAgent: (p) => this.execAgent(p),messageModel: this.messageModel,+ queueSubAgentSteer: (p) =>+ queueSubAgentSteer({ db: this.db, userId: this.userId, workspaceId: this.workspaceId }, p),threadModel: this.threadModel,userId: this.userId,};diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.tsindex 1b581e2920a..3819b7c0c38 100644--- a/apps/server/src/services/aiAgent/steerQueue/index.ts+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts@@ -61,6 +61,12 @@ export interface QueuedFollowUp extends SteerQueueEntry {*/composer?: { editorData?: Record<string, unknown>; filesPreview?: Record<string, unknown>[] };request: QueuedFollowUpRequest;+ /**+ * Queued by a parent agent for its running `callSubAgent` child (see+ * `queueSubAgentSteer`), so it is written for exactly that run: it joins the+ * child's turn as it is, whatever device or executor settings the run has.+ */+ subAgentSteer?: boolean;/** Who queued it; only the run owner's own follow-ups are started for them. */userId: string;}diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts b/apps/server/src/services/aiAgent/steerQueue/inject.test.tsindex 474f8a5a5f6..252f914359d 100644--- a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts+++ b/apps/server/src/services/aiAgent/steerQueue/inject.test.ts@@ -64,6 +64,23 @@ describe('canJoinRunningTurn', () => {expect(canJoinRunningTurn(followUp('a', 1), state)).toBe(true);});+ it('takes a parent’s steer instruction whatever the sub-agent run’s settings', () => {+ const subAgentRun = {+ ...state,+ host: { acceptsFileWorks: true, clientProtocol: 2 },+ } as AgentState;+ const steer = { ...followUp('a', 1), subAgentSteer: true };++ expect(canJoinRunningTurn(followUp('a', 1), subAgentRun)).toBe(false);+ expect(canJoinRunningTurn(steer, subAgentRun)).toBe(true);+ expect(+ canJoinRunningTurn(+ { ...steer, request: { ...steer.request, agentId: 'agt-2' } },+ subAgentRun,+ ),+ ).toBe(false);+ });+it.each([['an attachment', { fileIds: ['f1'] }],[diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.ts b/apps/server/src/services/aiAgent/steerQueue/inject.tsindex 61be164ec2d..8aea763ccd8 100644--- a/apps/server/src/services/aiAgent/steerQueue/inject.ts+++ b/apps/server/src/services/aiAgent/steerQueue/inject.ts@@ -83,6 +83,7 @@ export const canJoinRunningTurn = (entry: QueuedFollowUp, state: AgentState): boconst runAgentId = state.origin?.agentId;if (!request.agentId || !runAgentId || request.agentId !== runAgentId) return false;+ if (entry.subAgentSteer) return true;return matchesRunningTurnSettings(request, state);};diff --git a/apps/server/src/services/aiAgent/steerQueue/subAgent.test.ts b/apps/server/src/services/aiAgent/steerQueue/subAgent.test.tsnew file mode 100644index 00000000000..e76da62ec1c--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/subAgent.test.ts@@ -0,0 +1,167 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { SteerQueueWriteUnknownError } from '@/server/services/redis/steerQueue';++import { queueSubAgentSteer } from './subAgent';++const mocks = vi.hoisted(() => ({+ append: vi.fn(),+ isRunAlive: vi.fn(),+ isSealed: vi.fn(),+ remove: vi.fn(),+}));++vi.mock('@/server/services/redis', () => ({+ redisService: {+ steerQueue: { append: mocks.append, isSealed: mocks.isSealed, remove: mocks.remove },+ },+}));+vi.mock('./liveRuns', () => ({ isRunAlive: mocks.isRunAlive }));++const ctx = { db: {} as any, userId: 'user-1', workspaceId: 'ws-1' };+const params = {+ agentId: 'agt-1',+ instruction: 'Only cover 2025',+ operationId: 'op-child',+ threadId: 'thd-sub',+ topicId: 'tpc-1',+};+const scope = { threadId: 'thd-sub', topicId: 'tpc-1', userId: 'user-1' };++describe('queueSubAgentSteer', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.append.mockResolvedValue(1);+ mocks.isRunAlive.mockResolvedValue(true);+ mocks.isSealed.mockResolvedValue(false);+ });++ it('queues the instruction behind the running sub-agent on its thread', async () => {+ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({ queued: true });++ expect(mocks.append).toHaveBeenCalledWith(+ scope,+ expect.objectContaining({+ request: expect.objectContaining({ agentId: 'agt-1', prompt: 'Only cover 2025' }),+ subAgentSteer: true,+ userId: 'user-1',+ }),+ 'op-child',+ );+ expect(mocks.remove).not.toHaveBeenCalled();+ });++ it('takes the instruction back when the run ended meanwhile', async () => {+ mocks.isRunAlive.mockResolvedValue(false);+ mocks.remove.mockResolvedValue(true);++ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({+ queued: false,+ reason: 'ended',+ });+ const entry = mocks.append.mock.calls[0][1];+ expect(mocks.remove).toHaveBeenCalledWith(scope, entry.id);+ });++ it('takes the instruction back when the run already made its last read', async () => {+ // Still alive by its row, but past the final queue read it seals before.+ mocks.isSealed.mockResolvedValue(true);+ mocks.remove.mockResolvedValue(true);++ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({+ queued: false,+ reason: 'ended',+ });+ expect(mocks.isSealed).toHaveBeenCalledWith('op-child');+ });++ it('takes the instruction back when the seal cannot be read', async () => {+ mocks.isSealed.mockRejectedValue(new Error('redis down'));+ mocks.remove.mockResolvedValue(true);++ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({+ queued: false,+ reason: 'ended',+ });+ });++ it('retries an unknown write with the same entry id', async () => {+ mocks.append+ .mockRejectedValueOnce(new SteerQueueWriteUnknownError(new Error('timeout')))+ .mockResolvedValueOnce(1);++ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({ queued: true });+ const [first, second] = mocks.append.mock.calls;+ expect(second[1].id).toBe(first[1].id);+ });++ it('reports it queued when the retry finds the earlier write already taken', async () => {+ mocks.append+ .mockRejectedValueOnce(new SteerQueueWriteUnknownError(new Error('timeout')))+ .mockResolvedValueOnce('taken');++ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({ queued: true });+ expect(mocks.remove).not.toHaveBeenCalled();+ });++ it.each([+ [+ 'the retry is unknown too',+ () => mocks.append.mockRejectedValue(new SteerQueueWriteUnknownError(new Error('timeout'))),+ ],+ [+ 'Redis is gone on the retry',+ () =>+ mocks.append+ .mockRejectedValueOnce(new SteerQueueWriteUnknownError(new Error('timeout')))+ .mockResolvedValueOnce(undefined),+ ],+ ])('reports the outcome unknown, not unavailable, when %s', async (_case, arrange) => {+ arrange();++ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({+ queued: false,+ reason: 'unknown',+ });+ });++ it.each([+ [+ 'the run’s status cannot be read',+ () => mocks.isRunAlive.mockRejectedValue(new Error('db down')),+ ],+ [+ 'the take-back fails',+ () => {+ mocks.isRunAlive.mockResolvedValue(false);+ mocks.remove.mockRejectedValue(new Error('redis down'));+ },+ ],+ ])('reports a stored instruction unknown when %s after the append', async (_case, arrange) => {+ arrange();++ // Stored already, and the run may be following it: a resend could run it twice.+ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({+ queued: false,+ reason: 'unknown',+ });+ expect(mocks.append).toHaveBeenCalledTimes(1);+ });++ it('reports it queued when the ending run already took it', async () => {+ mocks.isRunAlive.mockResolvedValue(false);+ mocks.remove.mockResolvedValue(false);++ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({ queued: true });+ });++ it.each([+ ['the queue is full', () => mocks.append.mockResolvedValue('full'), 'full'],+ ['Redis is missing', () => mocks.append.mockResolvedValue(undefined), 'unavailable'],+ ['the write was taken back', () => mocks.append.mockResolvedValue('notStored'), 'unavailable'],+ ])('refuses when %s', async (_case, arrange, reason) => {+ arrange();++ await expect(queueSubAgentSteer(ctx, params)).resolves.toEqual({ queued: false, reason });+ });+});diff --git a/apps/server/src/services/aiAgent/steerQueue/subAgent.ts b/apps/server/src/services/aiAgent/steerQueue/subAgent.tsnew file mode 100644index 00000000000..6cfdf1f5e61--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/subAgent.ts@@ -0,0 +1,117 @@+import { randomUUID } from 'node:crypto';++import debug from 'debug';++import { redisService } from '@/server/services/redis';+import { SteerQueueWriteUnknownError } from '@/server/services/redis/steerQueue';++import type { ComposerRunContext } from '../composerRun';+import type { QueuedFollowUp } from './index';+import { isRunAlive } from './liveRuns';++const log = debug('lobe-server:steer-queue');++export type SubAgentSteerOutcome =+ | { queued: true }+ /**+ * `ended`: the run finished before the instruction was stored, so the caller+ * continues the thread with a new run instead. `full` / `unavailable`: it+ * was not stored and nothing will deliver it. `unknown`: the write failed+ * twice and may still have landed, or it landed and the check after it+ * failed — the run may already be following it, so sending it again could+ * run it twice.+ */+ | { queued: false; reason: 'ended' | 'full' | 'unavailable' | 'unknown' };++/**+ * Queue a parent agent's new instruction behind its running `callSubAgent`+ * child, on the child's isolation thread. The child's step loop takes it in+ * before its next LLM call (`injectQueuedFollowUp`), the same way a running+ * conversation takes in a follow-up the user typed behind it.+ */+export const queueSubAgentSteer = async (+ ctx: Pick<ComposerRunContext, 'db' | 'userId' | 'workspaceId'>,+ params: {+ agentId: string;+ groupId?: string | null;+ instruction: string;+ operationId: string;+ threadId: string;+ topicId: string;+ },+): Promise<SubAgentSteerOutcome> => {+ const { agentId, groupId, instruction, operationId, threadId, topicId } = params;+ const scope = { threadId, topicId, userId: ctx.userId };+ const entry: QueuedFollowUp = {+ createdAt: Date.now(),+ id: randomUUID(),+ request: {+ agentId,+ appContext: { groupId: groupId ?? undefined, threadId, topicId },+ prompt: instruction,+ },+ subAgentSteer: true,+ userId: ctx.userId,+ };++ const appendOnce = async () => {+ try {+ return await redisService.steerQueue.append(scope, entry, operationId);+ } catch (error) {+ if (!(error instanceof SteerQueueWriteUnknownError)) throw error;+ log('[%s] Steer for thread %s may not be queued: %O', operationId, threadId, error);+ return 'unknown' as const;+ }+ };++ // A timed-out write may still have landed. Retrying with the same entry id+ // appends at most once, so it settles the outcome without a duplicate.+ let length = await appendOnce();+ const uncertain = length === 'unknown';+ if (uncertain) length = await appendOnce();+ if (length === 'unknown') return { queued: false, reason: 'unknown' };+ // A retry that finds the entry already taken: the run read the earlier write.+ if (length === 'taken') return { queued: true };+ if (length === 'full') return { queued: false, reason: 'full' };+ if (length === undefined || length === 'notStored') {+ // After an unknown write, no Redis on the retry proves nothing either way.+ return { queued: false, reason: uncertain && length === undefined ? 'unknown' : 'unavailable' };+ }++ // The run may have ended between the caller's check and the append, after+ // its last chance to read the queue: it seals itself before its final read+ // (`steerQueue.seal`), or its row already says it ended. Take the entry back+ // so the caller can start a new run with it; losing the take-back means the+ // run already took it. The entry is stored by now, so a check that fails+ // leaves it unknown whether the run follows it: a resend could run it twice.+ try {+ if (+ (await isPastLastRead(ctx, operationId)) &&+ (await redisService.steerQueue.remove(scope, entry.id))+ ) {+ return { queued: false, reason: 'ended' };+ }+ } catch (error) {+ log(+ '[%s] Checking the steer for thread %s after queuing failed: %O',+ operationId,+ threadId,+ error,+ );+ return { queued: false, reason: 'unknown' };+ }++ log('[%s] Queued a steer instruction for thread %s', operationId, threadId);+ return { queued: true };+};++/** A seal that cannot be read counts as set: taking the entry back is the safe side. */+const isPastLastRead = async (+ ctx: Pick<ComposerRunContext, 'db' | 'userId' | 'workspaceId'>,+ operationId: string,+): Promise<boolean> => {+ const sealed = await redisService.steerQueue.isSealed(operationId).catch(() => true);+ if (sealed !== false) return true;++ return !(await isRunAlive({ db: ctx.db, workspaceId: ctx.workspaceId }, ctx.userId, operationId));+};diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.tsindex 05a648df449..3ca0ed110e4 100644--- a/apps/server/src/services/aiAgent/subAgentRuns.ts+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts@@ -37,6 +37,7 @@ import {pickThreadCarryOver,type ThreadCarryOver,} from './hooks/threadRunHooks';+import type { SubAgentSteerOutcome } from './steerQueue/subAgent';import type { InternalExecAgentParams } from './types';const HEADLESS_INTERVENTION: UserInterventionConfig = { approvalMode: 'headless' };@@ -49,6 +50,15 @@ export interface SubAgentRunDeps {/** The facade's `execAgent` — thread runs delegate the actual turn to it. */execAgent: (params: InternalExecAgentParams) => Promise<ExecAgentResult>;messageModel: MessageModel;+ /** Queue an instruction behind a running sub-agent (`queueSubAgentSteer`). */+ queueSubAgentSteer: (params: {+ agentId: string;+ groupId?: string | null;+ instruction: string;+ operationId: string;+ threadId: string;+ topicId: string;+ }) => Promise<SubAgentSteerOutcome>;threadModel: ThreadModel;userId: string;}@@ -120,9 +130,10 @@ type ThreadRow = NonNullable<Awaited<ReturnType<ThreadModel['findById']>>>;* Take over an earlier `callSubAgent` isolation thread for a new turn, so the* same sub-agent continues on its preserved history.*- * Refuses threads outside the parent's topic/agent, threads not created by- * `callSubAgent` (group members, `callAgent` children, …), and threads whose- * previous run is still going. The final compare-and-set claim makes+ * Refuses threads outside the parent's topic/agent and threads not created by+ * `callSubAgent` (group members, `callAgent` children, …). A thread whose+ * previous run is still going is not claimed: its run comes back as `running`,+ * for the caller to steer instead. The final compare-and-set claim makes* concurrent follow-ups to one sub-agent race-safe.** Returns what the thread carries (its spawning tool call and the usage it@@ -165,12 +176,13 @@ const findCallSubAgentThread = async (const readSubAgentThreadRun = async (deps: Pick<SubAgentRunDeps, 'agentOperationModel'>,thread: ThreadRow,-): Promise<{ operationId?: string; running: boolean }> => {+): Promise<{ operationId?: string; ownerId?: string; running: boolean }> => {const operationId = (thread.metadata as ThreadMetadata | null)?.operationId;const operation = operationId ? await deps.agentOperationModel.findById(operationId) : null;return {operationId,+ ownerId: operation?.userId ?? undefined,running: operation? isAgentOperationInFlight(operation.status): thread.status === ThreadStatus.Processing,@@ -189,28 +201,45 @@ const isStopping = async (deps: SubAgentRunDeps, operationId: string): Promise<bconst claimSubAgentThread = async (deps: SubAgentRunDeps,params: { agentId: string; startedAt: string; threadId: string; topicId: string },-): Promise<{ error: string } | { thread: ThreadRow; carryOver: ThreadCarryOver }> => {+): Promise<+ | { error: string }+ | { running: { operationId: string } }+ | { thread: ThreadRow; carryOver: ThreadCarryOver }+ | { claimLost: true }+> => {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 { 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.`;+ const {+ operationId: previousOperationId,+ ownerId,+ running: stillRunning,+ } = await readSubAgentThreadRun(deps, thread);if (stillRunning) {+ // A `processing` thread without an operation id names no run to queue behind.+ if (!previousOperationId) {+ return { error: `Sub-agent "${threadId}" is still starting. Try again in a moment.` };+ }// 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))) {+ // right after cancelSubAgent can still find it live. Queuing behind it would+ // strand the instruction: the stopped run never reads its queue again.+ if (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 };+ // The run reads its steer queue as the member whose turn started it; an+ // instruction from another member's turn would be queued where it never looks.+ if (ownerId && ownerId !== deps.userId) {+ return {+ error: `Sub-agent "${threadId}" is running for another member's turn and cannot take your instruction while it runs. Wait for its result, then send this instruction again; its history is kept.`,+ };+ }+ return { running: { operationId: previousOperationId } };}const carryOver = pickThreadCarryOver(previousMetadata);@@ -220,7 +249,65 @@ const claimSubAgentThread = async ({ ...carryOver, startedAt },);- return claimed ? { thread, carryOver } : { error: busyError };+ // Another follow-up started a run on the thread first; the caller re-reads it.+ return claimed ? { thread, carryOver } : { claimLost: true };+};++const STEER_REFUSALS: Record<'full' | 'unavailable' | 'unknown', (threadId: string) => string> = {+ full: (threadId) =>+ `Sub-agent "${threadId}" already has too many instructions waiting. Wait for its result before sending another.`,+ unavailable: (threadId) =>+ `The instruction could not be queued for sub-agent "${threadId}". Wait for its result, then send it again.`,+ unknown: (threadId) =>+ `The instruction may or may not have reached sub-agent "${threadId}". Do not send it again yet: wait for its result and check whether it followed the instruction.`,+};++/**+ * Continue a `callSubAgent` thread with a new instruction: claim it for a new+ * run when its previous run has ended, or — while that run is still going —+ * queue the instruction behind it, to be read before its next LLM call+ * (`steered`). A run that ends while the instruction is being queued, or a+ * claim lost to a concurrent follow-up, is re-read once.+ */+const continueSubAgentThread = async (+ deps: SubAgentRunDeps,+ params: {+ agentId: string;+ groupId?: string | null;+ instruction: string;+ startedAt: string;+ threadId: string;+ topicId: string;+ },+): Promise<+ | { error: string }+ | { steered: { operationId: string } }+ | { thread: ThreadRow; carryOver: ThreadCarryOver }+> => {+ const { groupId, instruction, ...claimParams } = params;+ const { threadId } = claimParams;++ for (let attempt = 0; attempt < 2; attempt++) {+ const claim = await claimSubAgentThread(deps, claimParams);+ if ('claimLost' in claim) continue;+ if (!('running' in claim)) return claim;++ const { operationId } = claim.running;+ const outcome = await deps.queueSubAgentSteer({+ agentId: claimParams.agentId,+ groupId,+ instruction,+ operationId,+ threadId,+ topicId: claimParams.topicId,+ });+ if (outcome.queued) return { steered: { operationId } };+ if (outcome.reason !== 'ended') return { error: STEER_REFUSALS[outcome.reason](threadId) };+ }++ return {+ error: `Sub-agent "${threadId}" is finishing its run or busy with another instruction. Wait for its result, then send the instruction again.`,+ };};export interface CancelSubAgentRunDeps extends Pick<@@ -351,8 +438,8 @@ export const cancelSubAgentThreadRun = async (}// 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.+ // steer the sub-agent right away: a follow-up is refused while the stopped run+ // is still finishing, 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@@ -413,8 +500,11 @@ export const execAgentThreadRun = async (// The new instruction lands as the next user turn on that thread, so the// sub-agent keeps its full history. Its original source message stays the// thread anchor; this run reports to the new placeholder (`parentMessageId`).- const claim = await claimSubAgentThread(deps, {+ // While its previous run is still going, the instruction steers that run.+ const claim = await continueSubAgentThread(deps, {agentId,+ groupId,+ instruction,startedAt,threadId: continueThreadId,topicId,@@ -442,6 +532,32 @@ export const execAgentThreadRun = async (};}+ // Still running: the instruction waits in its queue and joins that run's+ // next step. No new run, so the running one keeps reporting its result.+ if ('steered' in claim) {+ log('%s: steered running thread %s', options.logScope, continueThreadId);+ // The call returned without starting a run; hooks still see it end.+ if (parentOperationId) {+ hookDispatcher+ .dispatch(parentOperationId, 'afterCallAgent', {+ agentId,+ operationId: parentOperationId,+ subOperationId: claim.steered.operationId,+ success: true,+ threadId: continueThreadId,+ userId: deps.userId,+ })+ .catch(() => {});+ }+ return {+ assistantMessageId: '',+ operationId: claim.steered.operationId,+ steered: true,+ success: true,+ threadId: continueThreadId,+ };+ }+thread = claim.thread;carryOver = claim.carryOver;log('%s: continuing thread %s', options.logScope, thread.id);diff --git a/apps/server/src/services/redis/steerQueue.ts b/apps/server/src/services/redis/steerQueue.tsindex 71f2852484c..b75b2c3fcf3 100644--- a/apps/server/src/services/redis/steerQueue.ts+++ b/apps/server/src/services/redis/steerQueue.ts@@ -554,6 +554,42 @@ export const steerQueue = {return { operationIds: [...operationIds], total: items.length + drained };},+ /**+ * Marks `operationId` as past its last queue read. A run seals itself before+ * that read and unseals when the read took an entry in; a writer checks+ * {@link steerQueue.isSealed} after its append, so an entry appended after+ * the read is always taken back by its writer.+ *+ * @throws when Redis is unavailable+ */+ async seal(operationId: string): Promise<void> {+ const redis = await getClient();+ if (!redis) throw new Error('Redis is unavailable to seal a run');++ await redis.set(RedisKeys.agentSteer.sealedRun(operationId), '1', {+ px: QUEUE_TTL_SECONDS * 1000,+ });+ },++ /** Undoes {@link steerQueue.seal}: the run reads its queue again. */+ async unseal(operationId: string): Promise<void> {+ const redis = await getClient();+ if (!redis) throw new Error('Redis is unavailable to unseal a run');++ await redis.del(RedisKeys.agentSteer.sealedRun(operationId));+ },++ /**+ * Whether `operationId` is past its last queue read (see+ * {@link steerQueue.seal}); `undefined` without Redis.+ */+ async isSealed(operationId: string): Promise<boolean | undefined> {+ const redis = await getClient();+ if (!redis) return;++ return (await redis.get(RedisKeys.agentSteer.sealedRun(operationId))) !== null;+ },+/** Number of entries `operationId` would take; `0` without Redis. */async length(scope: SteerQueueScope, operationId: string): Promise<number> {const redis = await getClient();diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/backgroundSubAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/backgroundSubAgent.test.tsindex d5bcd07acbf..e150b6f8eaa 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/backgroundSubAgent.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/backgroundSubAgent.test.ts@@ -11,7 +11,7 @@ vi.mock('@/database/models/message', () => ({listBackgroundSubAgentCalls: async ({ topicId }: { topicId: string }) => {// Let concurrent checks interleave, as real database reads do.await new Promise((resolve) => setTimeout(resolve, 5));- return (placeholders.get(topicId) ?? []).map((id) => ({ id }));+ return (placeholders.get(topicId) ?? []).map((id) => ({ id, state: { threadId: id } }));},};}),@@ -51,6 +51,26 @@ describe('startBackgroundSubAgent', () => {expect(placeholders.get('topic-batch')).toHaveLength(MAX_RUNNING_BACKGROUND_SUB_AGENTS);});+ it('lets a call steer one of its running background sub-agents at the limit', async () => {+ const ids = Array.from({ length: MAX_RUNNING_BACKGROUND_SUB_AGENTS }, (_, i) => `full-${i}`);+ placeholders.set('topic-full', ids);+ const continueOn = (continuesThreadId: string) =>+ startBackgroundSubAgent({+ continuesThreadId,+ db: {} as any,+ retryHint: 'Retry in the foreground.',+ start: async () => 'steered',+ topicId: 'topic-full',+ userId: 'user-1',+ });++ // Steering adds no run; continuing a thread that is not running would.+ await expect(continueOn('full-2')).resolves.toEqual({ result: 'steered' });+ await expect(continueOn('thread-done')).resolves.toEqual({+ refusal: expect.objectContaining({ code: 'BACKGROUND_SUB_AGENT_LIMIT' }),+ });+ });+it('keeps the queue moving after a start throws', async () => {const failing = startBackgroundSubAgent({db: {} as any,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.tsindex b5610120f3d..aedbe00e1cd 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts@@ -1021,7 +1021,7 @@ describe('lobeAgentRuntime', () => {it('explains why an earlier sub-agent could not be continued', async () => {const runtime = lobeAgentRuntime.factory(baseContext);const run = vi.fn().mockResolvedValue({- error: 'Sub-agent "thread-1" is still running.',+ error: 'Sub-agent "thread-1" already has too many instructions waiting.',started: false,threadId: 'thread-1',});@@ -1033,10 +1033,35 @@ describe('lobeAgentRuntime', () => {expect(result.deferred).toBeUndefined();expect(result.content).toBe(- 'Sub-agent could not be continued: Sub-agent "thread-1" is still running.',+ 'Sub-agent could not be continued: Sub-agent "thread-1" already has too many instructions waiting.',);});+ it('returns a receipt instead of parking when it steers a running sub-agent', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);+ const run = vi.fn().mockResolvedValue({+ started: true,+ steered: true,+ subOperationId: 'sub-op-1',+ threadId: 'thread-1',+ toolMessageId: 'tool-msg-steer',+ });++ const result = await runtime.callSubAgent(+ { description: 'Correct course', instruction: 'Only cover 2025', subAgentId: 'thread-1' },+ { ...baseContext, subAgent: { run } } as ToolExecutionContext,+ );++ expect(result.deferred).toBeUndefined();+ expect(result).toMatchObject({+ state: { status: 'completed', steered: true, threadId: 'thread-1' },+ success: true,+ toolMessageId: 'tool-msg-steer',+ });+ expect(result.content).toContain('queued');+ expect(result.content).toContain('<sub_agent id="thread-1" />');+ });+// GPT-family models fill every declared field, so "start a new sub-agent"// arrives as `subAgentId: ""` rather than an omitted key.it.each(['', ' '])('starts a new sub-agent when subAgentId is blank (%j)', async (blank) => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/backgroundSubAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/backgroundSubAgent.tsindex 155f88b04e7..8d3e023e63a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/backgroundSubAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/backgroundSubAgent.ts@@ -14,6 +14,12 @@ export interface BackgroundSubAgentRefusal {}interface BackgroundSubAgentCheckParams {+ /**+ * The sub-agent thread this call continues (`subAgentId`). While that thread+ * still runs in the background, the call steers it or replaces its run, so it+ * adds no run to the count.+ */+ continuesThreadId?: string;db: LobeChatDatabase;groupId?: string | null;/** How to call the tool in the foreground instead, for the refusal text. */@@ -35,7 +41,8 @@ interface BackgroundSubAgentCheckParams {export const checkBackgroundSubAgentAllowed = async (params: BackgroundSubAgentCheckParams,): Promise<BackgroundSubAgentRefusal | undefined> => {- const { db, groupId, retryHint, threadId, topicId, userId, workspaceId } = params;+ const { continuesThreadId, db, groupId, retryHint, threadId, topicId, userId, workspaceId } =+ params;if (groupId) {return {@@ -54,7 +61,9 @@ export const checkBackgroundSubAgentAllowed = async (scope: 'running',topicId,});- if (running.length >= MAX_RUNNING_BACKGROUND_SUB_AGENTS) {+ const continuesRunning =+ !!continuesThreadId && running.some((call) => call.state?.threadId === continuesThreadId);+ if (running.length >= MAX_RUNNING_BACKGROUND_SUB_AGENTS && !continuesRunning) {return {code: 'BACKGROUND_SUB_AGENT_LIMIT',message: `${running.length} background runs are already going in this conversation (limit ${MAX_RUNNING_BACKGROUND_SUB_AGENTS}). Wait for their results to arrive, or ${retryHint.charAt(0).toLowerCase()}${retryHint.slice(1)}`,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.tsindex ad2f465838b..65b4b731d95 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -11,6 +11,7 @@ import type {import {buildAnalyzeMediaContent,buildBackgroundSubAgentReceipt,+ buildSteeredSubAgentReceipt,createMediaFileItemsFromMessage,createUrlMediaFileItems,formatMediaUrlValidationError,@@ -338,6 +339,7 @@ class LobeAgentExecutionRuntime {let runResult: Awaited<ReturnType<typeof startRun>>;if (background) {const outcome = await startBackgroundSubAgent({+ continuesThreadId: subAgentId,db: this.db,groupId: this.groupId,retryHint: 'Call callSubAgent again without runInBackground to wait for the result.',@@ -352,7 +354,7 @@ class LobeAgentExecutionRuntime {} else {runResult = await startRun();}- const { started, error, threadId, subOperationId, toolMessageId } = runResult;+ const { started, error, steered, threadId, subOperationId, toolMessageId } = runResult;// The child op failed to start — no completion bridge will ever fire to// backfill a placeholder, so we must NOT defer/park here. Return a normal@@ -366,6 +368,17 @@ class LobeAgentExecutionRuntime {);}+ // Steered a sub-agent that is still running: the instruction joins its next+ // step, and the running call reports the answer. Nothing to wait for here.+ if (steered) {+ return {+ content: buildSteeredSubAgentReceipt(threadId),+ state: { status: 'completed', steered: true, threadId },+ success: true,+ toolMessageId,+ };+ }+// Detached: the receipt is the whole tool result and the parent keeps going.// It goes into the placeholder the runner created (it anchors the thread);// the answer reaches the parent later as its own message.diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex 63fde17ac77..941b38ec7e0 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -62,6 +62,12 @@ export interface ServerSubAgentRunResult {* instead of parking the parent — otherwise the parent hangs forever.*/started: boolean;+ /**+ * `subAgentId` named a sub-agent that is still running: no child was forked,+ * the instruction was queued for that run's next step instead. The caller+ * returns a receipt rather than parking on a result.+ */+ steered?: boolean;/** The spawned child operation id. */subOperationId?: string;/** The isolation thread holding the sub-agent's full message trace. */diff --git a/packages/agent-runtime/src/agents/graph/GraphAgent.ts b/packages/agent-runtime/src/agents/graph/GraphAgent.tsindex 34dabbb1aa7..f41b3122d06 100644--- a/packages/agent-runtime/src/agents/graph/GraphAgent.ts+++ b/packages/agent-runtime/src/agents/graph/GraphAgent.ts@@ -1,9 +1,6 @@import { ToolNameResolver } from '@lobechat/context-engine';import type { AgentGraph, AgentGraphEdge, AgentGraphNode } from '@lobechat/types';import { AGENT_GRAPH_ROOT_NODE_ID } from '@lobechat/types/agent/graph';-import { toJsonSafe } from '../../utils/json';-import type { UnknownRecord } from '../../utils/object';-import { isRecord } from '../../utils/object';import Ajv from 'ajv';import type {@@ -15,6 +12,9 @@ import type {GeneralAgentCallLLMInstructionPayload,GeneralAgentConfig,} from '../../types';+import { toJsonSafe } from '../../utils/json';+import type { UnknownRecord } from '../../utils/object';+import { isRecord } from '../../utils/object';import { selectRunTools, selectToolManifestMap } from '../../utils/operationToolSet';import { GeneralChatAgent } from '../GeneralChatAgent';import {@@ -84,6 +84,11 @@ interface GraphRuntimeState {graphContext: GraphContext;graphState: GraphState;instructionCount: number;+ /**+ * The graph's terminal node, kept for readers outside the agent that hold+ * only the state (see `isGraphAgentIntermediateResult`).+ */+ terminalNode?: string;}interface ReducerInput {@@ -137,6 +142,47 @@ interface PromptObject {[key: string]: PromptValue;}+/**+ * Whether a tool-free LLM result of this run belongs to a `GraphAgent` node+ * before its terminal one: the graph routes it on to the next node, so the run+ * does not end there. `false` for a run no graph drives, and at the terminal+ * node, whose result can finish the graph. A state written without the+ * terminal node counts every graph result as intermediate.+ */+export const isGraphAgentIntermediateResult = (state: Readonly<AgentState>): boolean => {+ const runtime = state.metadata?.[GRAPH_RUNTIME_STATE_KEY] as GraphRuntimeState | undefined;+ if (!runtime) return false;+ if (!runtime.terminalNode) return true;++ const { graphState } = runtime;+ return !('currentNode' in graphState) || graphState.currentNode !== runtime.terminalNode;+};++/**+ * Whether this run's latest LLM result is a `GraphAgent` node's output+ * extraction (`<node>:extract`) rather than the node's own work. The graph+ * parses that reply as the node's structured output and accepts it only as an+ * `llm_result`, so nothing may join the conversation at it. `false` for a run+ * no graph drives.+ */+export const isGraphAgentOutputExtraction = (state: Readonly<AgentState>): boolean => {+ const runtime = state.metadata?.[GRAPH_RUNTIME_STATE_KEY] as GraphRuntimeState | undefined;++ return runtime?.graphState.phase === 'node_out';+};++/**+ * Whether this run's graph is at a node's own work (`node_in`): the LLM call it+ * is about to make ends in a tool result or an answer, never in the graph's+ * finish. A graph whose terminal node routes back to another node reaches this+ * again after its terminal answer. `false` for a run no graph drives.+ */+export const isGraphAgentNodeWork = (state: Readonly<AgentState>): boolean => {+ const runtime = state.metadata?.[GRAPH_RUNTIME_STATE_KEY] as GraphRuntimeState | undefined;++ return runtime?.graphState.phase === 'node_in';+};+/*** GraphAgent is a graph-level orchestrator over the normal AgentRuntime loop.*@@ -722,7 +768,10 @@ export class GraphAgent implements Agent {private updateGraphRuntimeState(state: AgentState, graphRuntimeState: GraphRuntimeState): void {state.metadata ??= {};- state.metadata[GRAPH_RUNTIME_STATE_KEY] = graphRuntimeState;+ state.metadata[GRAPH_RUNTIME_STATE_KEY] = {+ ...graphRuntimeState,+ terminalNode: this.graph.terminal,+ };}private updateEdgeTraversalCount(diff --git a/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.intermediateResult.test.ts b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.intermediateResult.test.tsnew file mode 100644index 00000000000..42a424b8e94--- /dev/null+++ b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.intermediateResult.test.ts@@ -0,0 +1,243 @@+import { AGENT_GRAPH_ROOT_NODE_ID } from '@lobechat/types/agent/graph';+import { describe, expect, it } from 'vitest';++import type { AgentRuntimeContext, AgentState } from '../../../types';+import {+ GraphAgent,+ isGraphAgentIntermediateResult,+ isGraphAgentNodeWork,+ isGraphAgentOutputExtraction,+} from '../GraphAgent';++const llmResult: AgentRuntimeContext = {+ payload: {+ hasToolsCalling: false,+ result: { content: 'done', tool_calls: [] },+ toolsCalling: [],+ },+ phase: 'llm_result',+};++const createState = (): AgentState =>+ ({+ messages: [{ content: 'Draft, then review.', role: 'user' }],+ operationId: 'test-operation',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ tools: [],+ }) as unknown as AgentState;++describe('isGraphAgentIntermediateResult', () => {+ it('tells a graph node before the terminal one from the terminal node', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: {+ edges: [+ { from: AGENT_GRAPH_ROOT_NODE_ID, instruction: 'Write a draft.', to: 'draft' },+ { from: 'draft', instruction: 'Review the draft.', to: 'review' },+ ],+ fields: {},+ name: 'draft-review',+ nodes: { draft: { type: 'llm' }, review: { type: 'llm' } },+ terminal: 'review',+ },+ operationId: 'test-operation',+ });+ const state = createState();++ await agent.runner({ phase: 'init' } as AgentRuntimeContext, state);+ // The draft node's tool-free result moves the graph on to the review node.+ expect(isGraphAgentIntermediateResult(state)).toBe(true);++ await agent.runner(llmResult, state);+ // The review node's result can finish the graph.+ expect(isGraphAgentIntermediateResult(state)).toBe(false);++ await expect(agent.runner(llmResult, state)).resolves.toMatchObject({ type: 'finish' });+ });++ it('answers a steer joined at an intermediate node again on that node', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: {+ edges: [+ { from: AGENT_GRAPH_ROOT_NODE_ID, instruction: 'Write a draft.', to: 'draft' },+ { from: 'draft', instruction: 'Review the draft.', to: 'review' },+ ],+ fields: {},+ name: 'draft-review',+ nodes: { draft: { type: 'llm' }, review: { type: 'llm' } },+ terminal: 'review',+ },+ operationId: 'test-operation',+ });+ const state = createState();+ await agent.runner({ phase: 'init' } as AgentRuntimeContext, state);++ // The draft node answered and a steer joined before the graph moved on.+ state.messages.push(+ { content: 'first draft', role: 'assistant' } as any,+ { content: 'Make it shorter.', role: 'user' } as any,+ );+ const steered = await agent.runner(+ { payload: { parentMessageId: 'msg-steer' }, phase: 'user_input' } as AgentRuntimeContext,+ state,+ );++ // The draft node runs again with its own stage context, not the review node.+ expect(steered).toMatchObject({+ payload: { additionalContexts: expect.anything() },+ type: 'call_llm',+ });+ expect(JSON.stringify(steered)).toContain('Write a draft.');+ expect(JSON.stringify(steered)).not.toContain('Review the draft.');+ expect(isGraphAgentIntermediateResult(state)).toBe(true);++ // Its new answer moves the graph on as usual.+ await agent.runner(llmResult, state);+ expect(isGraphAgentIntermediateResult(state)).toBe(false);+ });++ it('is false for a run no graph drives', () => {+ expect(isGraphAgentIntermediateResult(createState())).toBe(false);+ });+});++describe('isGraphAgentOutputExtraction', () => {+ it('tells a node’s output extraction from the node’s own work', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: {+ edges: [+ {+ from: AGENT_GRAPH_ROOT_NODE_ID,+ instruction: 'Write a draft.',+ output: { fields: [{ field: 'draft' }] },+ to: 'draft',+ },+ { from: 'draft', instruction: 'Review the draft.', to: 'review' },+ ],+ fields: { draft: { desc: 'The draft.', schema: { type: 'string' } } },+ name: 'draft-review',+ nodes: { draft: { type: 'llm' }, review: { type: 'llm' } },+ terminal: 'review',+ },+ operationId: 'test-operation',+ });+ const state = createState();++ await agent.runner({ phase: 'init' } as AgentRuntimeContext, state);+ // The draft node is doing its own work.+ expect(isGraphAgentOutputExtraction(state)).toBe(false);++ // A reply without the output JSON makes the graph ask for it.+ await expect(agent.runner(llmResult, state)).resolves.toMatchObject({+ stepLabel: 'draft:extract',+ type: 'call_llm',+ });+ expect(isGraphAgentOutputExtraction(state)).toBe(true);++ await agent.runner(+ {+ ...llmResult,+ payload: {+ ...(llmResult.payload as object),+ result: { content: '```json\n{"draft":"d"}\n```' },+ },+ } as AgentRuntimeContext,+ state,+ );+ // The extracted output moved the graph on to the review node's own work.+ expect(isGraphAgentOutputExtraction(state)).toBe(false);+ });++ it('is false for a run no graph drives', () => {+ expect(isGraphAgentOutputExtraction(createState())).toBe(false);+ });+});++describe('isGraphAgentNodeWork', () => {+ // The terminal review node can send the work back to the draft node.+ const createLoopingAgent = () =>+ new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: {+ edges: [+ { from: AGENT_GRAPH_ROOT_NODE_ID, instruction: 'Write a draft.', to: 'draft' },+ {+ from: 'draft',+ instruction: 'Review the draft.',+ output: { fields: [{ field: 'verdict' }] },+ to: 'review',+ },+ {+ condition: {+ properties: { verdict: { const: 'revise' } },+ required: ['verdict'],+ type: 'object',+ },+ from: 'review',+ instruction: 'Revise the draft.',+ to: 'draft',+ },+ ],+ fields: { verdict: { desc: 'Review verdict.', schema: { type: 'string' } } },+ name: 'draft-review-loop',+ nodes: { draft: { type: 'llm' }, review: { type: 'llm' } },+ terminal: 'review',+ },+ operationId: 'test-operation',+ });+ const answer = (content: string) =>+ ({+ ...llmResult,+ payload: { ...(llmResult.payload as object), result: { content } },+ }) as AgentRuntimeContext;++ it('is true again when the terminal node routes back to another node', async () => {+ const agent = createLoopingAgent();+ const state = createState();++ await agent.runner({ phase: 'init' } as AgentRuntimeContext, state);+ await agent.runner(answer('first draft'), state);+ // The terminal review node is working: its answer is the run's last read.+ expect(isGraphAgentNodeWork(state)).toBe(true);+ expect(isGraphAgentIntermediateResult(state)).toBe(false);++ await expect(+ agent.runner(answer('```json\n{"verdict":"revise"}\n```'), state),+ ).resolves.toMatchObject({ type: 'call_llm' });+ // The review sent the work back: the draft node's work starts in this step.+ expect(isGraphAgentNodeWork(state)).toBe(true);+ expect(isGraphAgentIntermediateResult(state)).toBe(true);+ });++ it('is false once the terminal node finishes the graph', async () => {+ const agent = createLoopingAgent();+ const state = createState();++ await agent.runner({ phase: 'init' } as AgentRuntimeContext, state);+ await agent.runner(answer('first draft'), state);+ await expect(+ agent.runner(answer('```json\n{"verdict":"ok"}\n```'), state),+ ).resolves.toMatchObject({ type: 'finish' });++ expect(isGraphAgentNodeWork(state)).toBe(false);+ });++ it('is false during a node’s output extraction and for a run no graph drives', async () => {+ const agent = createLoopingAgent();+ const state = createState();++ await agent.runner({ phase: 'init' } as AgentRuntimeContext, state);+ await agent.runner(answer('first draft'), state);+ // A review answer without the verdict JSON makes the graph ask for it.+ await expect(agent.runner(answer('looks fine'), state)).resolves.toMatchObject({+ stepLabel: 'review:extract',+ });++ expect(isGraphAgentNodeWork(state)).toBe(false);+ expect(isGraphAgentNodeWork(createState())).toBe(false);+ });+});diff --git a/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.tsindex e29ea578f58..88cf1dbf75f 100644--- a/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts+++ b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts@@ -691,11 +691,8 @@ describe('GraphAgent', () => {expect(getFragment(stepEight, 'graph_runtime_guidance')).toMatchObject({wrapper: { attributes: { stage: 'plan' } },});- expect(Object.keys(getGraphRuntimeState(state) ?? {}).sort()).toEqual([- 'graphContext',- 'graphState',- 'instructionCount',- ]);+ const keys = Object.keys(getGraphRuntimeState(state) ?? {}).sort();+ expect(keys).toEqual(['graphContext', 'graphState', 'instructionCount', 'terminalNode']);});it('should use four-step guidance cadence near a finite node budget', async () => {diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.tsindex 342fd0bc775..d2a0130cf29 100644--- a/packages/builtin-tool-lobe-agent/src/manifest.ts+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts@@ -253,7 +253,7 @@ export const LobeAgentManifest: BuiltinToolManifest = {},subAgentId: {description:- 'Optional. The id from the `<sub_agent id="..." />` tag at the end of an earlier callSubAgent result. Sends `instruction` as a new message to that same sub-agent, which keeps all of its previous work and history — use it to continue a sub-agent that stopped or failed, ask it to hand over what it has found so far, or follow up on its answer. Leave empty (or omit) to start a new sub-agent; never invent an id.',+ 'Optional. The id from the `<sub_agent id="..." />` tag at the end of an earlier callSubAgent result. Sends `instruction` as a new message to that same sub-agent, which keeps all of its previous work and history — use it to continue a sub-agent that stopped or failed, ask it to hand over what it has found so far, or follow up on its answer. If that sub-agent is still running, the instruction is queued and it reads it at its next step to correct course. Leave empty (or omit) to start a new sub-agent; never invent an id.',type: 'string',},runInBackground: {@@ -279,7 +279,7 @@ export const LobeAgentManifest: BuiltinToolManifest = {},{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`.',+ 'Cancel a sub-agent that is still running — typically one started with `runInBackground` — whose work is no longer needed. It stops at its next step, no result is delivered for it, and its history is kept. To correct a sub-agent that has gone off track, do not cancel it: send the correction with `callSubAgent` and the same `subAgentId` while it runs.',name: LobeAgentApiName.cancelSubAgent,parameters: {additionalProperties: false,diff --git a/packages/builtin-tool-lobe-agent/src/subAgentReference.ts b/packages/builtin-tool-lobe-agent/src/subAgentReference.tsindex e31904f3899..77076b5922e 100644--- a/packages/builtin-tool-lobe-agent/src/subAgentReference.ts+++ b/packages/builtin-tool-lobe-agent/src/subAgentReference.ts@@ -51,3 +51,14 @@ export const buildBackgroundSubAgentReceipt = (subAgentId?: string): string => {'Started in the background. The result will be delivered to you as a new message when it finishes — do not wait or poll for it. Continue with other work, or end your turn and tell the user what is running.';return subAgentId ? appendSubAgentReference(receipt, subAgentId) : receipt;};++/**+ * Tool result of `callSubAgent({ subAgentId })` sent to a sub-agent that is+ * still running: the instruction joins that run instead of starting a new one,+ * so the answer comes the way the running call already reports it.+ */+export const buildSteeredSubAgentReceipt = (subAgentId: string): string =>+ appendSubAgentReference(+ 'The sub-agent is still running, so this instruction was queued for it. It reads it at its next step and continues with it in mind; its result arrives the way its running call reports it — do not wait or poll for it here.',+ subAgentId,+ );diff --git a/packages/builtin-tool-lobe-agent/src/systemRole.ts b/packages/builtin-tool-lobe-agent/src/systemRole.tsindex 0d5898cadb0..ea7ececb5b8 100644--- a/packages/builtin-tool-lobe-agent/src/systemRole.ts+++ b/packages/builtin-tool-lobe-agent/src/systemRole.ts@@ -48,11 +48,10 @@ You can dispatch **sub-agents** to handle long-running, multi-step work in isola- Every sub-agent result ends with \`<sub_agent id="..." />\`. Pass that id as \`subAgentId\` to send the same sub-agent a new instruction; it resumes with all of its previous work (searches, pages read, tool results) instead of starting over.- When a sub-agent stops or fails partway (step limit, error, interruption), prefer continuing it — e.g. ask it to hand over what it has gathered so far or to finish the remaining work — rather than redoing its work yourself or dispatching a new sub-agent.- 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.+- To correct a background sub-agent that is still running (it went off track, or the user changed what they want), pass its id as \`subAgentId\` with the correction; do not cancel it first. The instruction is queued and the sub-agent reads it at its next step, then keeps going with everything it has done so far; its result still arrives as before. Only send it to change course, never to check on progress.+- \`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). No result is delivered for a cancelled sub-agent.- Do not cancel a sub-agent just because it is taking a while.**Use sub-agents when:**diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.tsindex 554430199af..f4fae925fa7 100644--- a/packages/builtin-tool-lobe-agent/src/types.ts+++ b/packages/builtin-tool-lobe-agent/src/types.ts@@ -239,6 +239,11 @@ export interface CallSubAgentState extends SubAgentRunStats {*/sender?: { agentId: string; name: string };status?: 'pending' | 'completed' | 'error';+ /**+ * This call sent its instruction to a sub-agent that was still running: it+ * was queued for that run's next step, and the row only holds the receipt.+ */+ steered?: boolean;threadId: string;}diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 25ae41ebfc7..e08974ade16 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -737,6 +737,12 @@ export interface ExecSubAgentResult {error?: string;/** Operation ID for tracking execution status */operationId: string;+ /**+ * The thread's previous run was still going, so no run was started: the+ * instruction was queued behind that run (`operationId`) and joins it before+ * its next LLM call.+ */+ steered?: boolean;/** Whether the execution was created successfully */success: boolean;/** The Thread ID where the execution is isolated */