Skip to content

🀯 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.

♻️ refactor(agent): run callAgent as deferred tool (#15765)

Arvin Xu10b3cbda3ef6
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.md
index 65862dc1b93..5062794250d 100644
--- a/.agents/skills/agent-testing/SKILL.md
+++ b/.agents/skills/agent-testing/SKILL.md
@@ -111,7 +111,7 @@ First check the repo root for `.env`:
Do not start the standalone e2e server as the product under test.
Use `scripts/init-dev-env.sh`. It follows the e2e setup pattern β€” Postgres,
-migrations, auth/key-vault/S3 test env, seed user β€” but it is owned by this
+Redis, migrations, auth/key-vault/S3 test env, seed user β€” but it is owned by this
skill and starts the repo's dev server (`pnpm run dev:next` / `bun run dev`),
not `e2e/scripts/setup.ts --start`. The script hard-blocks when root `.env`
exists, so it cannot accidentally override a user's local config. When `.env`
@@ -132,19 +132,19 @@ fi
Bootstrap flow when no `.env` exists:
```bash
-# From repo root. Managed DB flow requires Docker Desktop.
+# From repo root. Managed Postgres/Redis flow requires Docker Desktop.
./.agents/skills/agent-testing/scripts/init-dev-env.sh setup-db
./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user
./.agents/skills/agent-testing/scripts/init-dev-env.sh dev
```
If using an existing Postgres instead of the managed Docker DB, set
-`DATABASE_URL` and skip `setup-db`:
+`DATABASE_URL` and `REDIS_URL`, then skip `setup-db`:
```bash
-DATABASE_URL=postgresql://... ./.agents/skills/agent-testing/scripts/init-dev-env.sh migrate
-DATABASE_URL=postgresql://... ./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user
-DATABASE_URL=postgresql://... ./.agents/skills/agent-testing/scripts/init-dev-env.sh dev
+DATABASE_URL=postgresql://... REDIS_URL=redis://... ./.agents/skills/agent-testing/scripts/init-dev-env.sh migrate
+DATABASE_URL=postgresql://... REDIS_URL=redis://... ./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user
+DATABASE_URL=postgresql://... REDIS_URL=redis://... ./.agents/skills/agent-testing/scripts/init-dev-env.sh dev
```
For backend-only checks, `dev-next` is available, but Web smoke needs the
@@ -170,6 +170,9 @@ Default script env:
- `APP_URL=http://localhost:3010`
- `DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres`
- `DATABASE_DRIVER=node`
+- `AGENT_RUNTIME_MODE=queue` so backend-only agent runtime checks use the
+ same queued execution path as production
+- `REDIS_URL=redis://localhost:6380` for queue-mode agent runtime state
- `FEATURE_FLAGS=-agent_self_iteration` so local smoke does not require QStash
- Local QStash defaults (`QSTASH_URL`, `QSTASH_TOKEN`, signing keys) are exported;
run `init-dev-env.sh qstash` in a separate terminal when the path under test
@@ -177,6 +180,7 @@ Default script env:
- `KEY_VAULTS_SECRET`, `AUTH_SECRET`, auth verification off
- S3 mock vars
- Managed DB container: `lobehub-agent-testing-postgres`
+- Managed Redis container: `lobehub-agent-testing-redis`
`seed-user` creates `[email protected]` / `TestPassword123!` with
onboarding already completed, plus a local API key in
diff --git a/.agents/skills/agent-testing/references/dev-server.md b/.agents/skills/agent-testing/references/dev-server.md
index 17514e36fb5..bb9de3f702b 100644
--- a/.agents/skills/agent-testing/references/dev-server.md
+++ b/.agents/skills/agent-testing/references/dev-server.md
@@ -48,14 +48,15 @@ curl -s -o /dev/null -w '%{http_code}' "$SERVER_URL/"
```bash
# Start backend only.
# With root .env: use the existing local config.
-pnpm run dev:next
+# Agent runtime queue mode is required to mirror production async execution.
+AGENT_RUNTIME_MODE=queue pnpm run dev:next
# Without root .env: use the self-contained agent-testing env.
./.agents/skills/agent-testing/scripts/init-dev-env.sh dev-next
# Full-stack SPA + backend. Required for Web smoke.
# With root .env:
-bun run dev
+AGENT_RUNTIME_MODE=queue bun run dev
# Without root .env:
./.agents/skills/agent-testing/scripts/init-dev-env.sh dev
@@ -91,6 +92,8 @@ in doubt.
| `ECONNREFUSED` | Server not running β€” start it |
| `EADDRINUSE` on the port | Already running β€” `lsof -ti:<port> \| xargs kill` first |
| Stale data / old behavior | Server needs a restart to pick up code changes |
+| Agent call runs inline | Set `AGENT_RUNTIME_MODE=queue`, make sure `REDIS_URL` is configured, then restart the server |
+| Queue mode needs Redis | Run `init-dev-env.sh setup-db`, or provide `REDIS_URL=redis://...` for an existing Redis |
| QStash workflow failures | Start `init-dev-env.sh qstash` and make sure dev server inherited the script's `QSTASH_*` env |
Marketplace/community endpoints are not part of the local agent-testing auth
diff --git a/.agents/skills/agent-testing/scripts/init-dev-env.sh b/.agents/skills/agent-testing/scripts/init-dev-env.sh
index ec90140d4a7..c19c78b1d84 100755
--- a/.agents/skills/agent-testing/scripts/init-dev-env.sh
+++ b/.agents/skills/agent-testing/scripts/init-dev-env.sh
@@ -12,16 +12,16 @@
# Usage:
# init-dev-env.sh env # print shell exports
# init-dev-env.sh write [file] # write a source-able env file
-# init-dev-env.sh setup-db # start local Postgres and run migrations
+# init-dev-env.sh setup-db # start local Postgres/Redis and run migrations
# init-dev-env.sh migrate # run DB migrations against the configured DB
# init-dev-env.sh seed-user # seed the baseline test user + CLI API key
# init-dev-env.sh qstash # run local Upstash QStash dev server
# init-dev-env.sh dev-next # exec `pnpm run dev:next` with this env
# init-dev-env.sh dev # exec `bun run dev` with this env
-# init-dev-env.sh clean-db # remove the managed Postgres container
+# init-dev-env.sh clean-db # remove the managed Postgres/Redis containers
#
# Overrides:
-# SERVER_PORT=3010 DB_PORT=5433 DB_CONTAINER=lobehub-agent-testing-postgres QSTASH_DEV_PORT=8080
+# SERVER_PORT=3010 DB_PORT=5433 DB_CONTAINER=lobehub-agent-testing-postgres REDIS_PORT=6380 REDIS_CONTAINER=lobehub-agent-testing-redis QSTASH_DEV_PORT=8080
set -euo pipefail
@@ -32,6 +32,9 @@ SERVER_PORT="${SERVER_PORT:-3010}"
DB_PORT="${DB_PORT:-5433}"
DB_CONTAINER="${DB_CONTAINER:-lobehub-agent-testing-postgres}"
DATABASE_URL="${DATABASE_URL:-postgresql://postgres:postgres@localhost:${DB_PORT}/postgres}"
+REDIS_PORT="${REDIS_PORT:-6380}"
+REDIS_CONTAINER="${REDIS_CONTAINER:-lobehub-agent-testing-redis}"
+REDIS_URL="${REDIS_URL:-redis://localhost:${REDIS_PORT}}"
ENV_FILE_DEFAULT="$REPO_ROOT/.records/env/agent-testing-dev.env"
CLI_ENV_FILE_DEFAULT="$REPO_ROOT/.records/env/agent-testing-cli.env"
AGENT_TESTING_API_KEY="${AGENT_TESTING_API_KEY:-sk-lh-agenttesting0001}"
@@ -54,6 +57,7 @@ guard_no_root_env() {
}
apply_env() {
+ export AGENT_RUNTIME_MODE="${AGENT_RUNTIME_MODE:-queue}"
export APP_URL="${APP_URL:-http://localhost:${SERVER_PORT}}"
export AUTH_EMAIL_VERIFICATION="${AUTH_EMAIL_VERIFICATION:-0}"
export AUTH_SECRET="${AUTH_SECRET:-agent-testing-local-auth-secret-32chars}"
@@ -69,6 +73,7 @@ apply_env() {
export QSTASH_NEXT_SIGNING_KEY="${QSTASH_NEXT_SIGNING_KEY:-$QSTASH_LOCAL_NEXT_SIGNING_KEY}"
export QSTASH_TOKEN="${QSTASH_TOKEN:-$QSTASH_LOCAL_TOKEN}"
export QSTASH_URL="${QSTASH_URL:-http://127.0.0.1:${QSTASH_DEV_PORT}}"
+ export REDIS_URL
export S3_ACCESS_KEY_ID="${S3_ACCESS_KEY_ID:-agent-testing-access-key}"
export S3_BUCKET="${S3_BUCKET:-agent-testing-bucket}"
export S3_ENDPOINT="${S3_ENDPOINT:-https://agent-testing-s3.localhost}"
@@ -78,6 +83,7 @@ apply_env() {
env_keys() {
printf '%s\n' \
APP_URL \
+ AGENT_RUNTIME_MODE \
AUTH_EMAIL_VERIFICATION \
AUTH_SECRET \
DATABASE_DRIVER \
@@ -92,6 +98,7 @@ env_keys() {
QSTASH_NEXT_SIGNING_KEY \
QSTASH_TOKEN \
QSTASH_URL \
+ REDIS_URL \
S3_ACCESS_KEY_ID \
S3_BUCKET \
S3_ENDPOINT \
@@ -137,6 +144,15 @@ wait_for_db() {
printf '\n'
}
+wait_for_redis() {
+ printf ' waiting for Redis'
+ until docker exec "$REDIS_CONTAINER" redis-cli ping > /dev/null 2>&1; do
+ printf '.'
+ sleep 1
+ done
+ printf '\n'
+}
+
start_db() {
require_docker
@@ -157,6 +173,25 @@ start_db() {
wait_for_db
}
+start_redis() {
+ require_docker
+
+ if docker ps --format '{{.Names}}' | grep -Fxq "$REDIS_CONTAINER"; then
+ ok "Redis container already running: $REDIS_CONTAINER"
+ elif docker ps -a --format '{{.Names}}' | grep -Fxq "$REDIS_CONTAINER"; then
+ docker start "$REDIS_CONTAINER" > /dev/null
+ ok "started existing Redis container: $REDIS_CONTAINER"
+ else
+ docker run -d \
+ --name "$REDIS_CONTAINER" \
+ -p "${REDIS_PORT}:6379" \
+ redis:7-alpine > /dev/null
+ ok "created Redis container: $REDIS_CONTAINER"
+ fi
+
+ wait_for_redis
+}
+
migrate_db() {
apply_env
cd "$REPO_ROOT"
@@ -327,9 +362,11 @@ cmd_status() {
apply_env
echo "agent-testing local dev env:"
note "APP_URL=$APP_URL"
+ note "AGENT_RUNTIME_MODE=$AGENT_RUNTIME_MODE"
note "DATABASE_URL=$DATABASE_URL"
note "PORT=$PORT"
note "QSTASH_URL=$QSTASH_URL"
+ note "REDIS_URL=$REDIS_URL"
if command -v docker > /dev/null 2>&1; then
ok "docker CLI available"
if docker ps --format '{{.Names}}' | grep -Fxq "$DB_CONTAINER"; then
@@ -337,6 +374,11 @@ cmd_status() {
else
note "managed Postgres is not running: $DB_CONTAINER"
fi
+ if docker ps --format '{{.Names}}' | grep -Fxq "$REDIS_CONTAINER"; then
+ ok "managed Redis running: $REDIS_CONTAINER"
+ else
+ note "managed Redis is not running: $REDIS_CONTAINER"
+ fi
else
bad "docker CLI is not available"
fi
@@ -373,6 +415,15 @@ cmd_clean_db() {
else
note "Postgres container not found: $DB_CONTAINER"
fi
+ if docker ps --format '{{.Names}}' | grep -Fxq "$REDIS_CONTAINER"; then
+ docker stop "$REDIS_CONTAINER" > /dev/null
+ fi
+ if docker ps -a --format '{{.Names}}' | grep -Fxq "$REDIS_CONTAINER"; then
+ docker rm "$REDIS_CONTAINER" > /dev/null
+ ok "removed Redis container: $REDIS_CONTAINER"
+ else
+ note "Redis container not found: $REDIS_CONTAINER"
+ fi
}
usage() {
@@ -391,6 +442,7 @@ case "$COMMAND" in
write) shift; write_env "${1:-}" ;;
setup-db)
start_db
+ start_redis
migrate_db
;;
migrate) migrate_db ;;
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 1b7035a95a2..104eedd532d 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -128,6 +128,7 @@ describe('RuntimeExecutors', () => {
mockMessageModel = {
create: vi.fn().mockResolvedValue({ id: 'msg-123' }),
+ deleteMessage: vi.fn().mockResolvedValue({ success: true }),
// call_llm does a parent existence preflight; return a truthy row by
// default so existing tests don't have to stub it.
findById: vi.fn().mockResolvedValue({ id: 'msg-existing' }),
@@ -4853,10 +4854,9 @@ describe('RuntimeExecutors', () => {
...overrides,
});
- it('call_tool sets stop:true in tool_result payload when tool returns execSubAgent state', async () => {
- // Simulate agentManagement.callAgent returning execSubAgent state
+ it('call_tool preserves stop:true for legacy execSubAgent state', async () => {
mockToolExecutionService.executeTool.mockResolvedValue({
- content: 'πŸš€ Triggered async task to call agent "target-agent"',
+ content: 'Legacy async task result',
executionTime: 10,
state: {
parentMessageId: 'tool-msg-id',
@@ -4897,13 +4897,112 @@ describe('RuntimeExecutors', () => {
expect((result.nextContext?.payload as any).stop).toBe(true);
});
+ it('call_tool lets server callAgent run as a deferred tool via the subAgent runner', async () => {
+ const mockExecVirtualSubAgent = vi
+ .fn()
+ .mockResolvedValue({ success: true, operationId: 'child-op', threadId: 'thread-child' });
+ const ctxWithCallback = {
+ ...ctx,
+ execVirtualSubAgent: mockExecVirtualSubAgent,
+ topicId: 'topic-123',
+ };
+
+ mockMessageModel.create.mockResolvedValueOnce({ id: 'tool-msg-id' });
+ mockToolExecutionService.executeTool.mockImplementation(
+ async (_payload: any, context: any) => {
+ const subAgent = await context.subAgent.run({
+ agentId: 'target-agent-id',
+ description: 'Call agent target-agent',
+ instruction: 'Do something useful',
+ timeout: 1_800_000,
+ });
+
+ return {
+ content: '',
+ deferred: true,
+ executionTime: 10,
+ state: {
+ status: 'pending',
+ subOperationId: subAgent.subOperationId,
+ targetAgentId: 'target-agent-id',
+ threadId: subAgent.threadId,
+ },
+ success: subAgent.started,
+ };
+ },
+ );
+
+ const executors = createRuntimeExecutors(ctxWithCallback);
+ const state = createMockState();
+ const instruction = {
+ payload: {
+ parentMessageId: 'assistant-msg-id',
+ toolCalling: {
+ apiName: 'callAgent',
+ arguments: JSON.stringify({
+ agentId: 'target-agent-id',
+ instruction: 'Do something useful',
+ runAsTask: true,
+ }),
+ id: 'tool-call-1',
+ identifier: 'lobe-agent-management',
+ type: 'default' as const,
+ },
+ },
+ type: 'call_tool' as const,
+ };
+
+ const result = await executors.call_tool!(instruction, state);
+
+ expect(mockMessageModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'parent-agent-id',
+ plugin: expect.objectContaining({
+ apiName: 'callAgent',
+ identifier: 'lobe-agent-management',
+ }),
+ pluginState: { status: 'pending' },
+ parentId: 'assistant-msg-id',
+ role: 'tool',
+ tool_call_id: 'tool-call-1',
+ topicId: 'topic-123',
+ }),
+ );
+ expect(mockExecVirtualSubAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'target-agent-id',
+ instruction: 'Do something useful',
+ parentMessageId: 'tool-msg-id',
+ parentOperationId: 'op-123',
+ title: 'Call agent target-agent',
+ topicId: 'topic-123',
+ }),
+ );
+ expect(result.newState.status).toBe('waiting_for_async_tool');
+ expect(result.newState.pendingToolsCalling).toEqual([
+ expect.objectContaining({
+ apiName: 'callAgent',
+ id: 'tool-call-1',
+ identifier: 'lobe-agent-management',
+ }),
+ ]);
+ expect(result.events).toEqual([
+ expect.objectContaining({
+ canResume: true,
+ reason: 'async_tool',
+ type: 'interrupted',
+ }),
+ ]);
+ expect(result.nextContext).toBeUndefined();
+ });
+
it('exec_sub_agent executor creates task message and calls execSubAgent callback', async () => {
- const mockExecSubAgentTask = vi
+ const mockExecSubAgent = vi
.fn()
.mockResolvedValue({ success: true, operationId: 'child-op', threadId: 'thread-child' });
const ctxWithCallback = {
...ctx,
- execSubAgent: mockExecSubAgentTask,
+ execSubAgent: mockExecSubAgent,
topicId: 'topic-123',
};
@@ -4929,6 +5028,9 @@ describe('RuntimeExecutors', () => {
expect(mockMessageModel.create).toHaveBeenCalledWith(
expect.objectContaining({
agentId: 'parent-agent-id',
+ metadata: expect.objectContaining({
+ targetAgentId: 'target-agent-id',
+ }),
role: 'task',
parentId: 'tool-msg-id',
topicId: 'topic-123',
@@ -4936,7 +5038,7 @@ describe('RuntimeExecutors', () => {
);
// execSubAgent callback fired with targetAgentId
- expect(mockExecSubAgentTask).toHaveBeenCalledWith(
+ expect(mockExecSubAgent).toHaveBeenCalledWith(
expect.objectContaining({
agentId: 'target-agent-id',
instruction: 'Do something useful',
@@ -4950,10 +5052,10 @@ describe('RuntimeExecutors', () => {
});
it('exec_sub_agent blocks nested dispatch when current state is already a sub-agent', async () => {
- const mockExecSubAgentTask = vi.fn();
+ const mockExecSubAgent = vi.fn();
const ctxWithCallback = {
...ctx,
- execSubAgentTask: mockExecSubAgentTask,
+ execSubAgent: mockExecSubAgent,
topicId: 'topic-123',
};
@@ -4986,7 +5088,7 @@ describe('RuntimeExecutors', () => {
success: false,
});
expect(mockMessageModel.create).not.toHaveBeenCalled();
- expect(mockExecSubAgentTask).not.toHaveBeenCalled();
+ expect(mockExecSubAgent).not.toHaveBeenCalled();
});
it('exec_sub_agent gracefully skips dispatch when execSubAgent not injected', async () => {
diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverCallAgent.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverCallAgent.integration.test.ts
new file mode 100644
index 00000000000..0f4fd0dec6c
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverCallAgent.integration.test.ts
@@ -0,0 +1,284 @@
+// @vitest-environment node
+/**
+ * Integration test for the server `lobe-agent-management.callAgent` deferred
+ * execution flow.
+ *
+ * Verifies the full lifecycle end-to-end on the in-memory runtime:
+ * 1. Parent op LLM emits a `lobe-agent-management____callAgent` tool call.
+ * 2. The real server executor parks the parent, creates a pending tool
+ * placeholder, and forks the target agent as a child op.
+ * 3. The child op completes.
+ * 4. The completion bridge backfills the placeholder and resumes the parent.
+ * 5. The parent reaches `done`.
+ */
+import { type LobeChatDatabase } from '@lobechat/database';
+import { agentOperations, agents, messagePlugins, messages } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { and, eq } from 'drizzle-orm';
+import OpenAI from 'openai';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { inMemoryAgentStateManager } from '@/server/modules/AgentRuntime/InMemoryAgentStateManager';
+import { inMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';
+
+import { aiAgentRouter } from '../../../aiAgent';
+import { cleanupTestUser, createTestUser } from '../setup';
+import { createMockResponsesStream, waitForOperationComplete } from './helpers';
+
+process.env.OPENAI_API_KEY = 'sk-test-fake-api-key-for-testing';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ getFullFileUrl: vi.fn().mockImplementation((path: string) => (path ? `/files${path}` : null)),
+ })),
+}));
+
+let mockResponsesCreate: ReturnType<typeof vi.spyOn>;
+let serverDB: LobeChatDatabase;
+let userId: string;
+let parentAgentId: string;
+let targetAgentId: string;
+
+const TARGET_ANSWER = 'The target agent completed the delegated callAgent work.';
+const PARENT_FINAL = 'I received the target agent result and the delegated work is complete.';
+
+const createTestContext = () => ({ jwtPayload: { userId }, userId });
+
+const createCallAgentResponse = () => {
+ const responseId = `resp_call_agent_${Date.now()}`;
+ const msgItemId = `msg_call_agent_${Date.now()}`;
+ const callId = 'call_agent_1';
+ const fnCall = {
+ arguments: JSON.stringify({
+ agentId: targetAgentId,
+ instruction: 'Handle the delegated backend integration task.',
+ runAsTask: true,
+ taskTitle: 'Delegated backend integration task',
+ timeout: 30_000,
+ }),
+ call_id: callId,
+ name: 'lobe-agent-management____callAgent',
+ type: 'function_call',
+ };
+
+ return createMockResponsesStream([
+ {
+ response: {
+ created_at: Math.floor(Date.now() / 1000),
+ id: responseId,
+ model: 'gpt-5-pro',
+ object: 'response',
+ output: [],
+ status: 'in_progress',
+ },
+ type: 'response.created',
+ },
+ {
+ item: {
+ content: [],
+ id: msgItemId,
+ role: 'assistant',
+ status: 'in_progress',
+ type: 'message',
+ },
+ output_index: 0,
+ type: 'response.output_item.added',
+ },
+ {
+ content_index: 0,
+ delta: 'I will delegate this to the target agent.',
+ item_id: msgItemId,
+ output_index: 0,
+ type: 'response.output_text.delta',
+ },
+ { item: fnCall, output_index: 1, type: 'response.output_item.added' },
+ {
+ response: {
+ created_at: Math.floor(Date.now() / 1000),
+ id: responseId,
+ model: 'gpt-5-pro',
+ object: 'response',
+ output: [
+ {
+ content: [{ text: 'I will delegate this to the target agent.', type: 'output_text' }],
+ id: msgItemId,
+ role: 'assistant',
+ status: 'completed',
+ type: 'message',
+ },
+ fnCall,
+ ],
+ status: 'completed',
+ usage: { input_tokens: 30, output_tokens: 20, total_tokens: 50 },
+ },
+ type: 'response.completed',
+ },
+ ]);
+};
+
+const createFinalTextResponse = (content: string) => {
+ const responseId = `resp_final_${Date.now()}_${content.length}`;
+ const msgItemId = `msg_final_${Date.now()}_${content.length}`;
+
+ return createMockResponsesStream([
+ {
+ response: {
+ created_at: Math.floor(Date.now() / 1000),
+ id: responseId,
+ model: 'gpt-5-pro',
+ object: 'response',
+ output: [],
+ status: 'in_progress',
+ },
+ type: 'response.created',
+ },
+ {
+ content_index: 0,
+ delta: content,
+ item_id: msgItemId,
+ output_index: 0,
+ type: 'response.output_text.delta',
+ },
+ {
+ response: {
+ created_at: Math.floor(Date.now() / 1000),
+ id: responseId,
+ model: 'gpt-5-pro',
+ object: 'response',
+ output: [
+ {
+ content: [{ text: content, type: 'output_text' }],
+ id: msgItemId,
+ role: 'assistant',
+ status: 'completed',
+ type: 'message',
+ },
+ ],
+ status: 'completed',
+ usage: { input_tokens: 40, output_tokens: 20, total_tokens: 60 },
+ },
+ type: 'response.completed',
+ },
+ ]);
+};
+
+beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ const insertedAgents = await serverDB
+ .insert(agents)
+ .values([
+ {
+ chatConfig: {},
+ model: 'gpt-5-pro',
+ plugins: ['lobe-agent-management'],
+ provider: 'openai',
+ systemRole: 'You are a supervisor that delegates work to other agents.',
+ title: 'callAgent Supervisor',
+ userId,
+ },
+ {
+ chatConfig: {},
+ model: 'gpt-5-pro',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are the target agent. Return a concise result.',
+ title: 'callAgent Target',
+ userId,
+ },
+ ])
+ .returning();
+
+ parentAgentId = insertedAgents[0].id;
+ targetAgentId = insertedAgents[1].id;
+
+ mockResponsesCreate = vi.spyOn(OpenAI.Responses.prototype, 'create');
+});
+
+afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+ inMemoryAgentStateManager.clear();
+ inMemoryStreamEventManager.clear();
+});
+
+describe('Server callAgent deferred execution', () => {
+ it('parks the parent, runs the target agent, backfills the tool message and resumes', async () => {
+ let callCount = 0;
+ mockResponsesCreate.mockImplementation(() => {
+ callCount++;
+ if (callCount === 1) return Promise.resolve(createCallAgentResponse() as any);
+ if (callCount === 2) return Promise.resolve(createFinalTextResponse(TARGET_ANSWER) as any);
+ return Promise.resolve(createFinalTextResponse(PARENT_FINAL) as any);
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execAgent({
+ agentId: parentAgentId,
+ prompt: 'Delegate this work to the target agent and report back.',
+ userInterventionConfig: { approvalMode: 'headless' },
+ });
+ expect(createResult.success).toBe(true);
+
+ const finalState = await waitForOperationComplete(
+ inMemoryAgentStateManager,
+ createResult.operationId,
+ { maxWaitTime: 20_000 },
+ );
+
+ expect(finalState.status).toBe('done');
+ expect(finalState.pendingToolsCalling ?? []).toHaveLength(0);
+ expect(mockResponsesCreate).toHaveBeenCalledTimes(3);
+
+ const childOps = await serverDB
+ .select()
+ .from(agentOperations)
+ .where(eq(agentOperations.parentOperationId, createResult.operationId));
+ expect(childOps).toHaveLength(1);
+ expect(childOps[0]).toMatchObject({
+ agentId: targetAgentId,
+ status: 'done',
+ });
+
+ const toolMessages = await serverDB
+ .select({
+ content: messages.content,
+ role: messages.role,
+ state: messagePlugins.state,
+ identifier: messagePlugins.identifier,
+ apiName: messagePlugins.apiName,
+ toolCallId: messagePlugins.toolCallId,
+ })
+ .from(messages)
+ .innerJoin(messagePlugins, eq(messagePlugins.id, messages.id))
+ .where(
+ and(
+ eq(messages.userId, userId),
+ eq(messagePlugins.identifier, 'lobe-agent-management'),
+ eq(messagePlugins.apiName, 'callAgent'),
+ ),
+ );
+
+ expect(toolMessages).toHaveLength(1);
+ expect(toolMessages[0]).toMatchObject({
+ apiName: 'callAgent',
+ content: TARGET_ANSWER,
+ identifier: 'lobe-agent-management',
+ role: 'tool',
+ toolCallId: 'call_agent_1',
+ });
+ expect(toolMessages[0].state).toMatchObject({
+ status: 'completed',
+ threadId: childOps[0].threadId,
+ });
+ }, 30_000);
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
index 7e4d7ae837e..9f275e145de 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
@@ -74,6 +74,112 @@ describe('agentManagementRuntime', () => {
expect(PluginModel).toHaveBeenCalledWith(expect.anything(), 'user-1', 'workspace-1');
});
+ describe('callAgent', () => {
+ it('fails when the server sub-agent runner is unavailable', async () => {
+ const runtime = createRuntime();
+
+ const result = await runtime.callAgent(
+ {
+ agentId: 'agent-target',
+ instruction: 'Do delegated work',
+ runAsTask: true,
+ },
+ { toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: 'AGENT_CALL_UNAVAILABLE' });
+ });
+
+ it('returns a deferred tool result and forks the target agent through the sub-agent runner', async () => {
+ const run = vi.fn().mockResolvedValue({
+ started: true,
+ subOperationId: 'op-child',
+ threadId: 'thread-child',
+ });
+ const runtime = createRuntime();
+
+ const result = await runtime.callAgent(
+ {
+ agentId: 'agent-target',
+ instruction: 'Do delegated work',
+ runAsTask: true,
+ taskTitle: 'Delegated task',
+ timeout: 1234,
+ },
+ {
+ subAgent: { run },
+ toolManifestMap: {},
+ },
+ );
+
+ expect(run).toHaveBeenCalledWith({
+ agentId: 'agent-target',
+ description: 'Delegated task',
+ instruction: 'Do delegated work',
+ timeout: 1234,
+ });
+ expect(result).toMatchObject({
+ content: '',
+ deferred: true,
+ success: true,
+ });
+ expect(result.state).toMatchObject({
+ status: 'pending',
+ subOperationId: 'op-child',
+ targetAgentId: 'agent-target',
+ threadId: 'thread-child',
+ });
+ });
+
+ it('returns a non-deferred failure when the target agent cannot start', async () => {
+ const run = vi.fn().mockResolvedValue({
+ started: false,
+ threadId: '',
+ });
+ const runtime = createRuntime();
+
+ const result = await runtime.callAgent(
+ {
+ agentId: 'agent-target',
+ instruction: 'Do delegated work',
+ runAsTask: true,
+ },
+ {
+ subAgent: { run },
+ toolManifestMap: {},
+ },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({
+ code: 'AGENT_CALL_START_FAILED',
+ });
+ expect(result.deferred).toBeUndefined();
+ });
+
+ it('rejects nested server callAgent execution', async () => {
+ const run = vi.fn();
+ const runtime = createRuntime();
+
+ const result = await runtime.callAgent(
+ {
+ agentId: 'agent-target',
+ instruction: 'Do delegated work',
+ },
+ {
+ isSubAgent: true,
+ subAgent: { run },
+ toolManifestMap: {},
+ },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: 'NESTED_AGENT_CALL_NOT_ALLOWED' });
+ expect(run).not.toHaveBeenCalled();
+ });
+ });
+
describe('searchAgent', () => {
it('reports the real total and a pagination hint when more agents exist', async () => {
mockQueryAgents.mockResolvedValue(makeAgents(20));
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
index 995d4b237c6..ff7570417a5 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
@@ -43,20 +43,60 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
): Promise<ToolExecutionResult> => {
const { agentId, instruction, taskTitle, timeout } = params;
- // Server runtime always uses the legacy async invocation path because
- // there is no client-side `registerAfterCompletion` callback available
- // to execute synchronous agent calls.
+ if (ctx.isSubAgent) {
+ return {
+ content: 'Agent calls cannot be triggered from within another sub-agent.',
+ error: {
+ code: 'NESTED_AGENT_CALL_NOT_ALLOWED',
+ message: 'Agent calls cannot be triggered from within another sub-agent.',
+ },
+ success: false,
+ };
+ }
+
+ if (!ctx.subAgent) {
+ return {
+ content: 'Agent execution is not available in this runtime.',
+ error: { code: 'AGENT_CALL_UNAVAILABLE' },
+ success: false,
+ };
+ }
+
+ if (!instruction || typeof instruction !== 'string') {
+ return {
+ content: 'instruction is required.',
+ error: { code: 'INVALID_ARGUMENTS', message: 'instruction is required.' },
+ success: false,
+ };
+ }
+
+ const description = taskTitle || `Call agent ${agentId}`;
+ const { started, subOperationId, threadId } = await ctx.subAgent.run({
+ agentId,
+ description,
+ instruction,
+ timeout: timeout || 1_800_000,
+ });
+
+ if (!started) {
+ return {
+ content: `Agent "${agentId}" failed to start.`,
+ error: {
+ code: 'AGENT_CALL_START_FAILED',
+ message: `Agent "${agentId}" failed to start.`,
+ },
+ success: false,
+ };
+ }
+
return {
- content: `πŸš€ Triggered async task to call agent "${agentId}"${taskTitle ? `: ${taskTitle}` : ''}`,
+ content: '',
+ deferred: true,
state: {
- parentMessageId: ctx.messageId,
- task: {
- description: taskTitle || `Call agent ${agentId}`,
- instruction,
- targetAgentId: agentId,
- timeout: timeout || 1_800_000,
- },
- type: 'execSubAgent',
+ status: 'pending',
+ subOperationId,
+ targetAgentId: agentId,
+ threadId,
},
success: true,
};