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.

βͺ️ revert: enforce agent step execution deadlines (#17496)

YuTengjing92d51e0054a5
diff --git a/apps/server/src/agent-hono/handlers/__tests__/runStep.test.ts b/apps/server/src/agent-hono/handlers/__tests__/runStep.test.ts
index 49ff478820a..4cae3fa6837 100644
--- a/apps/server/src/agent-hono/handlers/__tests__/runStep.test.ts
+++ b/apps/server/src/agent-hono/handlers/__tests__/runStep.test.ts
@@ -1,13 +1,9 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- AgentStepTimeoutError,
- markAgentStepTimeoutHandled,
-} from '@/server/modules/AgentRuntime/stepDeadline';
import { AiAgentService } from '@/server/services/aiAgent';
-import { createRunStepHandler, runStep, runStepHealth } from '../runStep';
+import { runStep, runStepHealth } from '../runStep';
const mockGetOperationMetadata = vi.fn();
const mockExecuteStep = vi.fn();
@@ -233,30 +229,6 @@ describe('runStep handler', () => {
);
});
- it('forwards one shared deadline and AbortSignal to executeStep', async () => {
- mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });
- mockExecuteStep.mockResolvedValue({
- nextStepScheduled: false,
- state: { cost: { total: 0 }, status: 'done', stepCount: 1 },
- success: true,
- });
-
- const before = Date.now();
- const { ctx } = buildContext({ body: validBody });
- await runStep(ctx);
-
- expect(mockExecuteStep).toHaveBeenCalledWith(
- expect.objectContaining({
- deadlineAt: expect.any(Number),
- onStage: expect.any(Function),
- signal: expect.any(AbortSignal),
- }),
- );
- expect(mockExecuteStep.mock.calls[0][0].deadlineAt).toBeGreaterThanOrEqual(
- before + 8 * 60 * 1000,
- );
- });
-
it('unwraps QStash `body.payload` resume/intervention fields into executeStep', async () => {
mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });
mockExecuteStep.mockResolvedValue({
@@ -340,141 +312,6 @@ describe('runStep handler', () => {
stepIndex: 2,
});
});
-
- it('keeps a stalled metadata lookup retryable when the step deadline expires', async () => {
- mockGetOperationMetadata.mockImplementation(() => new Promise(() => {}));
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const handler = createRunStepHandler({ stepDeadlineMs: 10 });
- const { ctx } = buildContext({ body: validBody });
-
- const res = await handler(ctx);
-
- expect(res.status).toBe(500);
- expect(mockGetServerDB).not.toHaveBeenCalled();
- const warnings = warnSpy.mock.calls.map(([warning]) => JSON.parse(warning));
- const deadlineReachedIndex = warnings.findIndex(
- ({ event }) => event === 'agent.run_step.deadline_reached',
- );
- const timeoutIndex = warnings.findIndex(({ event }) => event === 'agent.run_step.timeout');
-
- expect(deadlineReachedIndex).toBeGreaterThanOrEqual(0);
- expect(timeoutIndex).toBeGreaterThan(deadlineReachedIndex);
- expect(warnings[deadlineReachedIndex]).toMatchObject({
- deadlineAt: expect.any(Number),
- elapsedMs: expect.any(Number),
- operationId: 'op-1',
- spanId: expect.any(String),
- stage: 'metadata.load',
- stageElapsedMs: expect.any(Number),
- stepIndex: 2,
- traceId: expect.any(String),
- });
- expect(warnings[timeoutIndex]).toMatchObject({
- event: 'agent.run_step.timeout',
- handled: false,
- operationId: 'op-1',
- spanId: expect.any(String),
- stage: 'metadata.load',
- stageElapsedMs: expect.any(Number),
- stepIndex: 2,
- traceId: expect.any(String),
- });
- errorSpy.mockRestore();
- warnSpy.mockRestore();
- });
-
- it('ACKs a handled step timeout with a stable error type and structured diagnostics', async () => {
- mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });
- mockExecuteStep.mockImplementation(({ signal }) => {
- return new Promise((_resolve, reject) => {
- signal.addEventListener(
- 'abort',
- () => {
- const error = signal.reason as AgentStepTimeoutError;
- markAgentStepTimeoutHandled(error);
- reject(error);
- },
- { once: true },
- );
- });
- });
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const handler = createRunStepHandler({ stepDeadlineMs: 10 });
- const { ctx, getCaptures } = buildContext({
- body: { ...validBody, timestamp: Date.now() - 125 },
- messageId: 'qstash-1',
- retried: '2',
- });
-
- const res = await handler(ctx);
-
- expect(res.status).toBe(200);
- expect(getCaptures()[0].body).toMatchObject({
- errorType: 'AgentStepTimeout',
- operationId: 'op-1',
- stage: 'runtime.execute',
- stepIndex: 2,
- success: false,
- });
- expect(JSON.parse(warnSpy.mock.calls.at(-1)![0])).toMatchObject({
- event: 'agent.run_step.timeout',
- operationId: 'op-1',
- qstashMessageId: 'qstash-1',
- stage: 'runtime.execute',
- stepIndex: 2,
- upstashRetried: '2',
- });
- warnSpy.mockRestore();
- });
-
- it('keeps an unhandled timeout retryable with a 500 response', async () => {
- mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });
- mockExecuteStep.mockRejectedValue(
- new AgentStepTimeoutError({ deadlineAt: Date.now(), stage: 'state.load' }),
- );
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const { ctx } = buildContext({ body: validBody });
-
- const res = await runStep(ctx);
-
- expect(res.status).toBe(500);
- expect(JSON.parse(warnSpy.mock.calls.at(-1)![0])).toMatchObject({
- event: 'agent.run_step.timeout',
- handled: false,
- operationId: 'op-1',
- stage: 'state.load',
- stepIndex: 2,
- });
- errorSpy.mockRestore();
- warnSpy.mockRestore();
- });
-
- it('keeps a timeout retryable when persisting its terminal error state fails', async () => {
- mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });
- const timeoutError = new AgentStepTimeoutError({
- deadlineAt: Date.now(),
- stage: 'state.error_save',
- });
- mockExecuteStep.mockRejectedValue(new Error('state save failed', { cause: timeoutError }));
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const { ctx } = buildContext({ body: validBody });
-
- const res = await runStep(ctx);
-
- expect(res.status).toBe(500);
- expect(JSON.parse(warnSpy.mock.calls.at(-1)![0])).toMatchObject({
- event: 'agent.run_step.timeout',
- handled: false,
- operationId: 'op-1',
- stage: 'state.error_save',
- stepIndex: 2,
- });
- errorSpy.mockRestore();
- warnSpy.mockRestore();
- });
});
describe('runStepHealth handler', () => {
diff --git a/apps/server/src/agent-hono/handlers/runStep.ts b/apps/server/src/agent-hono/handlers/runStep.ts
index 5e42c7c55f6..1657fc8a5ae 100644
--- a/apps/server/src/agent-hono/handlers/runStep.ts
+++ b/apps/server/src/agent-hono/handlers/runStep.ts
@@ -1,9 +1,3 @@
-import {
- context as otelContext,
- SpanStatusCode,
- trace as otelTrace,
-} from '@lobechat/observability-otel/api';
-import { tracer as agentRuntimeTracer } from '@lobechat/observability-otel/modules/agent-runtime';
import debug from 'debug';
import { eq } from 'drizzle-orm';
import type { Context } from 'hono';
@@ -11,12 +5,6 @@ import type { Context } from 'hono';
import { getServerDB } from '@/database/core/db-adaptor';
import { agentOperations } from '@/database/schemas/agentOperations';
import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';
-import {
- AgentStepTimeoutError,
- DEFAULT_AGENT_STEP_DEADLINE_MS,
- isAgentStepTimeoutError,
- raceWithAgentStepSignal,
-} from '@/server/modules/AgentRuntime/stepDeadline';
import { AiAgentService } from '@/server/services/aiAgent';
const log = debug('lobe-server:agent:run-step');
@@ -32,13 +20,6 @@ const getQStashMessageId = (c: Context): string | undefined =>
c.req.header('upstash-messageid') ??
c.req.header('message-id');
-const resolveAgentStepTimeoutError = (error: unknown): AgentStepTimeoutError | undefined => {
- if (isAgentStepTimeoutError(error)) return error;
- if (error instanceof Error && isAgentStepTimeoutError(error.cause)) return error.cause;
-
- return undefined;
-};
-
async function getOperationRowDiagnostic(operationId: string) {
try {
const serverDB = await getServerDB();
@@ -71,306 +52,155 @@ async function getOperationRowDiagnostic(operationId: string) {
}
}
-interface CreateRunStepHandlerOptions {
- stepDeadlineMs?: number;
-}
-
/**
* Execute a single agent step. Invoked by QStash with the body
* `{ operationId, stepIndex, context, humanInput?, approvedToolCall?, ... }`.
*
* Auth: `qstashAuth` on the route β€” QStash signature required.
*/
-export const createRunStepHandler = ({
- stepDeadlineMs = DEFAULT_AGENT_STEP_DEADLINE_MS,
-}: CreateRunStepHandlerOptions = {}) => {
- return async (c: Context): Promise<Response> => {
- const startTime = Date.now();
- const deadlineAt = startTime + stepDeadlineMs;
- const controller = new AbortController();
- const qstashMessageId = getQStashMessageId(c);
- const upstashRetried = c.req.header('upstash-retried') ?? null;
- const externalRetryCount = Number(upstashRetried ?? 0) || 0;
- let body: any;
- let currentStage = 'request.parse';
- let currentStageStartedAt = startTime;
- let operationId: string | undefined;
- let queueWaitMs: number | undefined;
- let stepIndex = 0;
-
- const runStepSpan = agentRuntimeTracer.startSpan('agent.run_step', {
- attributes: {
- 'agent.step.deadline_at': deadlineAt,
- 'agent.step.qstash_retried': externalRetryCount,
- },
- });
- const runStepContext = otelTrace.setSpan(otelContext.active(), runStepSpan);
- const reportStage = (stage: string) => {
- const now = Date.now();
- currentStage = stage;
- currentStageStartedAt = now;
- runStepSpan.addEvent('agent.run_step.stage', {
- 'agent.step.elapsed_ms': now - startTime,
- 'agent.step.stage': stage,
- });
- };
- const timeoutId = setTimeout(
- () => {
- const now = Date.now();
- const spanContext = runStepSpan.spanContext();
- const timeoutError = new AgentStepTimeoutError({
- deadlineAt,
- stage: currentStage,
- stageElapsedMs: now - currentStageStartedAt,
- });
-
- // Emit before aborting: some ownership-changing writes and post-commit
- // cleanup are deliberately not promise-raced. If one never returns,
- // the handler catch and span end below will not run before the platform
- // hard timeout, so this is the last reliable execution snapshot.
- console.warn(
- JSON.stringify({
- deadlineAt,
- elapsedMs: now - startTime,
- event: 'agent.run_step.deadline_reached',
- operationId,
- qstashMessageId,
- queueWaitMs,
- spanId: spanContext.spanId,
- stage: currentStage,
- stageElapsedMs: timeoutError.stageElapsedMs,
- stepIndex,
- traceId: spanContext.traceId,
- upstashRetried,
- }),
- );
-
- controller.abort(timeoutError);
- },
- Math.max(0, deadlineAt - Date.now()),
- );
-
- try {
- return await otelContext.with(runStepContext, async () => {
- try {
- body = await c.req.json();
- } catch {
- return c.json({ error: 'Invalid JSON body' }, 400);
- }
-
- try {
- // QStash nests resume/intervention fields under `body.payload` (see
- // QStashQueueServiceImpl.scheduleMessage), while `operationId`/`stepIndex`/
- // `context` stay at the top level. Merge so both shapes work β€” without this
- // the QStash path reads `resumeAsyncTool`/`approvedToolCall`/… as undefined
- // and never resumes a parked op. (The local queue spreads payload itself.)
- const mergedBody = { ...body, ...body.payload };
- const {
- approvedToolCall,
- asyncToolVerifyAttempt,
- context,
- finishAfterAsyncTool,
- groupMemberTimeout,
- humanInput,
- rejectAndContinue,
- rejectionReason,
- resumeAsyncTool,
- toolMessageId,
- verifyAsyncToolBarrier,
- } = mergedBody;
- operationId = mergedBody.operationId;
- stepIndex = mergedBody.stepIndex ?? 0;
- queueWaitMs =
- typeof body.timestamp === 'number' && Number.isFinite(body.timestamp)
- ? Math.max(0, startTime - body.timestamp)
- : undefined;
-
- runStepSpan.setAttributes({
- ...(operationId && { 'agent.operation.id': operationId }),
- ...(qstashMessageId && { 'agent.step.qstash_message_id': qstashMessageId }),
- ...(queueWaitMs !== undefined && { 'agent.step.queue_wait_ms': queueWaitMs }),
- 'agent.step.index': stepIndex,
- });
-
- if (!operationId) {
- return c.json({ error: 'operationId is required' }, 400);
- }
-
- log(`[${operationId}] Starting step ${stepIndex}`);
-
- reportStage('metadata.load');
- const coordinator = new AgentRuntimeCoordinator();
- const metadata = await raceWithAgentStepSignal(
- coordinator.getOperationMetadata(operationId),
- controller.signal,
- );
-
- if (!metadata?.userId) {
- reportStage('metadata.diagnostic');
- const dbRow = await raceWithAgentStepSignal(
- getOperationRowDiagnostic(operationId),
- controller.signal,
- );
- const diagnostic = {
- dbRow,
- event: 'agent.run_step.missing_operation_metadata',
- metadataHasUserId: Boolean(metadata?.userId),
- metadataPresent: Boolean(metadata),
- operationId,
- qstashMessageId,
- stepIndex,
- upstashRetried,
- };
+export async function runStep(c: Context): Promise<Response> {
+ const startTime = Date.now();
- log(`[${operationId}] Invalid operation or no userId found: %O`, diagnostic);
- console.warn(JSON.stringify(diagnostic));
- return c.json({ error: 'Invalid operation or unauthorized' }, 401);
- }
-
- reportStage('database.connect');
- const serverDB = await raceWithAgentStepSignal(getServerDB(), controller.signal);
- // Step through AiAgentService so the runtime keeps its `execSubAgent`
- // fork callback (needed by `lobe-agent.callSubAgent`). In QStash mode every
- // step is a fresh HTTP request, and a bare AgentRuntimeService would lose the
- // in-process callback β†’ SUB_AGENT_UNAVAILABLE.
- //
- // Thread the operation's workspace through so the runtime's models stay
- // workspace-scoped. Without it the worker is personal-scoped and the
- // parent-message lookup misses workspace-scoped rows β†’ ConversationParentMissing.
- const aiAgentService = new AiAgentService(serverDB, metadata.userId, {
- workspaceId: metadata.workspaceId,
- });
-
- reportStage('runtime.execute');
- const result = await aiAgentService.executeStep({
- approvedToolCall,
- asyncToolVerifyAttempt,
- context,
- deadlineAt,
- externalRetryCount,
- finishAfterAsyncTool,
- groupMemberTimeout,
- humanInput,
- onStage: reportStage,
- operationId,
- rejectAndContinue,
- rejectionReason,
- resumeAsyncTool,
- signal: controller.signal,
- stepIndex,
- toolMessageId,
- verifyAsyncToolBarrier,
- });
-
- // A non-stale lock conflict means another delivery is still executing this
- // operation. Keep the response retryable so QStash redelivers this step.
- if (result.locked) {
- log(`[${operationId}] Step ${stepIndex} locked by another instance, returning 429`);
- return c.json(
- { error: 'Step is currently being executed, retry later', operationId, stepIndex },
- 429,
- { 'Retry-After': '37' },
- );
- }
+ let body: any;
+ try {
+ body = await c.req.json();
+ } catch {
+ return c.json({ error: 'Invalid JSON body' }, 400);
+ }
- const executionTime = Date.now() - startTime;
- const responseData = {
- completed: result.state.status === 'done',
- error: result.state.status === 'error' ? result.state.error : undefined,
- executionTime,
- nextStepIndex: result.nextStepScheduled ? stepIndex + 1 : undefined,
- nextStepScheduled: result.nextStepScheduled,
- operationId,
- pendingApproval: result.state.pendingToolsCalling,
- pendingPrompt: result.state.pendingHumanPrompt,
- pendingSelect: result.state.pendingHumanSelect,
- status: result.state.status,
- stepIndex,
- success: result.success,
- totalCost: result.state.cost?.total || 0,
- totalSteps: result.state.stepCount,
- waitingForHuman: result.state.status === 'waiting_for_human',
- };
+ const externalRetryCount = Number(c.req.header('upstash-retried') ?? 0) || 0;
- log(
- `[${operationId}] Step ${stepIndex} completed (${executionTime}ms, status: ${result.state.status})`,
- );
+ try {
+ // QStash nests resume/intervention fields under `body.payload` (see
+ // QStashQueueServiceImpl.scheduleMessage), while `operationId`/`stepIndex`/
+ // `context` stay at the top level. Merge so both shapes work β€” without this
+ // the QStash path reads `resumeAsyncTool`/`approvedToolCall`/… as undefined
+ // and never resumes a parked op. (The local queue spreads payload itself.)
+ const {
+ operationId,
+ stepIndex = 0,
+ context,
+ humanInput,
+ approvedToolCall,
+ rejectionReason,
+ rejectAndContinue,
+ resumeAsyncTool,
+ finishAfterAsyncTool,
+ groupMemberTimeout,
+ toolMessageId,
+ verifyAsyncToolBarrier,
+ asyncToolVerifyAttempt,
+ } = { ...body, ...body.payload };
+
+ if (!operationId) {
+ return c.json({ error: 'operationId is required' }, 400);
+ }
- return c.json(responseData);
- } catch (error: unknown) {
- const executionTime = Date.now() - startTime;
- const timeoutError = resolveAgentStepTimeoutError(error);
+ log(`[${operationId}] Starting step ${stepIndex}`);
+
+ // Get userId from operation metadata stored in Redis
+ const coordinator = new AgentRuntimeCoordinator();
+ const metadata = await coordinator.getOperationMetadata(operationId);
+
+ if (!metadata?.userId) {
+ const dbRow = await getOperationRowDiagnostic(operationId);
+ const diagnostic = {
+ dbRow,
+ event: 'agent.run_step.missing_operation_metadata',
+ metadataHasUserId: Boolean(metadata?.userId),
+ metadataPresent: Boolean(metadata),
+ operationId,
+ qstashMessageId: getQStashMessageId(c),
+ stepIndex,
+ upstashRetried: c.req.header('upstash-retried') ?? null,
+ };
+
+ log(`[${operationId}] Invalid operation or no userId found: %O`, diagnostic);
+ console.warn(JSON.stringify(diagnostic));
+ return c.json({ error: 'Invalid operation or unauthorized' }, 401);
+ }
- if (timeoutError) {
- const spanContext = runStepSpan.spanContext();
- const diagnostic = {
- deadlineAt: timeoutError.deadlineAt,
- elapsedMs: executionTime,
- event: 'agent.run_step.timeout',
- handled: timeoutError.handled,
- operationId,
- qstashMessageId,
- queueWaitMs,
- spanId: spanContext.spanId,
- stage: timeoutError.stage,
- stageElapsedMs: timeoutError.stageElapsedMs,
- stepIndex,
- traceId: spanContext.traceId,
- upstashRetried,
- };
- console.warn(JSON.stringify(diagnostic));
- }
+ const serverDB = await getServerDB();
+ // Step through AiAgentService so the runtime keeps its `execSubAgent`
+ // fork callback (needed by `lobe-agent.callSubAgent`). In QStash mode every
+ // step is a fresh HTTP request, and a bare AgentRuntimeService would lose the
+ // in-process callback β†’ SUB_AGENT_UNAVAILABLE.
+ //
+ // Thread the operation's workspace through so the runtime's models stay
+ // workspace-scoped. Without it the worker is personal-scoped and the
+ // parent-message lookup misses workspace-scoped rows β†’ ConversationParentMissing.
+ const aiAgentService = new AiAgentService(serverDB, metadata.userId, {
+ workspaceId: metadata.workspaceId,
+ });
- // A handled timeout has completed the service's durable error
- // finalization and must ACK QStash. Unhandled timeouts (including an
- // error-state save failure carried as `cause`) fall through to 500 so
- // the same delivery remains retryable.
- if (timeoutError?.handled) {
- runStepSpan.recordException(timeoutError);
- runStepSpan.setStatus({ code: SpanStatusCode.ERROR, message: timeoutError.message });
+ const result = await aiAgentService.executeStep({
+ approvedToolCall,
+ asyncToolVerifyAttempt,
+ context,
+ externalRetryCount,
+ humanInput,
+ finishAfterAsyncTool,
+ groupMemberTimeout,
+ operationId,
+ rejectAndContinue,
+ rejectionReason,
+ resumeAsyncTool,
+ stepIndex,
+ toolMessageId,
+ verifyAsyncToolBarrier,
+ });
- return c.json(
- {
- error: timeoutError.message,
- errorType: timeoutError.errorType,
- executionTime,
- operationId,
- stage: timeoutError.stage,
- stepIndex,
- success: false,
- },
- 200,
- );
- }
+ // A non-stale lock conflict means another delivery is still executing this
+ // operation. Keep the response retryable so QStash redelivers this step.
+ if (result.locked) {
+ log(`[${operationId}] Step ${stepIndex} locked by another instance, returning 429`);
+ return c.json(
+ { error: 'Step is currently being executed, retry later', operationId, stepIndex },
+ 429,
+ { 'Retry-After': '37' },
+ );
+ }
- console.error('Error in execution: %O', error);
- const traceError = new Error('Agent step execution failed');
- traceError.name = error instanceof Error ? error.name : 'Error';
- runStepSpan.recordException(traceError);
- runStepSpan.setStatus({
- code: SpanStatusCode.ERROR,
- message: traceError.message,
- });
+ const executionTime = Date.now() - startTime;
+
+ const responseData = {
+ completed: result.state.status === 'done',
+ error: result.state.status === 'error' ? result.state.error : undefined,
+ executionTime,
+ nextStepIndex: result.nextStepScheduled ? stepIndex + 1 : undefined,
+ nextStepScheduled: result.nextStepScheduled,
+ operationId,
+ pendingApproval: result.state.pendingToolsCalling,
+ pendingPrompt: result.state.pendingHumanPrompt,
+ pendingSelect: result.state.pendingHumanSelect,
+ status: result.state.status,
+ stepIndex,
+ success: result.success,
+ totalCost: result.state.cost?.total || 0,
+ totalSteps: result.state.stepCount,
+ waitingForHuman: result.state.status === 'waiting_for_human',
+ };
- return c.json(
- {
- error: error instanceof Error ? error.message : String(error),
- executionTime,
- operationId,
- stepIndex,
- },
- 500,
- );
- }
- });
- } finally {
- clearTimeout(timeoutId);
- runStepSpan.end();
- }
- };
-};
+ log(
+ `[${operationId}] Step ${stepIndex} completed (${executionTime}ms, status: ${result.state.status})`,
+ );
-export const runStep = createRunStepHandler();
+ return c.json(responseData);
+ } catch (error: any) {
+ const executionTime = Date.now() - startTime;
+ console.error('Error in execution: %O', error);
+
+ return c.json(
+ {
+ error: error.message,
+ executionTime,
+ operationId: body?.operationId,
+ stepIndex: body?.stepIndex || 0,
+ },
+ 500,
+ );
+ }
+}
/**
* Health check for the agent execution path.
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts
index 23972b245f1..a1496096c05 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts
@@ -2,7 +2,6 @@ import type { ChatToolPayload } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { dispatchClientTool } from '../dispatchClientTool';
-import { AgentStepTimeoutError } from '../stepDeadline';
import type { IStreamEventManager } from '../types';
// Mock Redis before importing the SUT so the module-level getter sees it.
@@ -294,7 +293,7 @@ describe('dispatchClientTool', () => {
timeoutMs: 10_000_000,
});
- expect(sendToolExecute.mock.calls[0][1]).toMatchObject({ executionTimeoutMs: 480_000 });
+ expect(sendToolExecute.mock.calls[0][1]).toMatchObject({ executionTimeoutMs: 800_000 });
});
it('falls back to the 120s global default when ctx.timeoutMs is omitted', async () => {
@@ -313,26 +312,4 @@ describe('dispatchClientTool', () => {
expect(sendToolExecute.mock.calls[0][1]).toMatchObject({ executionTimeoutMs: 120_000 });
});
-
- it('stops a client-tool Redis wait when the containing step is aborted', async () => {
- const sendToolExecute = vi.fn().mockResolvedValue(undefined);
- const streamManager = makeStreamManager(sendToolExecute);
- const controller = new AbortController();
- mockBlpop.mockImplementation(() => new Promise(() => {}));
-
- const resultPromise = dispatchClientTool(makePayload(), {
- operationId: 'op-1',
- signal: controller.signal,
- streamManager,
- });
- await vi.waitFor(() => expect(mockBlpop).toHaveBeenCalled());
- const timeoutError = new AgentStepTimeoutError({
- deadlineAt: Date.now(),
- stage: 'tool.client.wait',
- });
- controller.abort(timeoutError);
-
- await expect(resultPromise).rejects.toBe(timeoutError);
- expect(mockDisconnect).toHaveBeenCalled();
- });
});
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/resolveToolTimeout.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/resolveToolTimeout.test.ts
index 59841e0b5f1..ece4a7f3ab2 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/resolveToolTimeout.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/resolveToolTimeout.test.ts
@@ -1,5 +1,5 @@
import { type LobeToolManifest } from '@lobechat/context-engine';
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import {
GLOBAL_DEFAULT_TIMEOUT_MS,
@@ -119,31 +119,4 @@ describe('resolveToolTimeoutMs', () => {
123_456,
);
});
-
- it('never exceeds the remaining containing-step budget', () => {
- const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(1_000_000);
-
- expect(
- resolveToolTimeoutMs({
- apiName: 'runCommand',
- args: { timeout: 240_000 },
- deadlineAt: 1_030_000,
- }),
- ).toBe(30_000);
-
- nowSpy.mockRestore();
- });
-
- it('allows the remaining step budget to override the normal one-second floor', () => {
- const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(1_000_000);
-
- expect(
- resolveToolTimeoutMs({
- apiName: 'runCommand',
- deadlineAt: 1_000_250,
- }),
- ).toBe(250);
-
- nowSpy.mockRestore();
- });
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts
deleted file mode 100644
index 6874fd115ef..00000000000
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import type { LLMTraceInput } from '@lobechat/agent-runtime';
-import type * as AgentRuntimeObservability from '@lobechat/observability-otel/modules/agent-runtime';
-import { ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK } from '@lobechat/observability-otel/modules/agent-runtime';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { RuntimeExecutorContext } from '../context';
-import { ServerLLMTransport } from './ServerLLMTransport';
-
-const mocks = vi.hoisted(() => {
- const chatSpan = {
- addEvent: vi.fn(),
- end: vi.fn(),
- recordException: vi.fn(),
- setAttribute: vi.fn(),
- setAttributes: vi.fn(),
- setStatus: vi.fn(),
- };
-
- return {
- chatSpan,
- startSpan: vi.fn(() => chatSpan),
- };
-});
-
-vi.mock('@lobechat/observability-otel/modules/agent-runtime', async (importOriginal) => {
- const actual = await importOriginal<typeof AgentRuntimeObservability>();
-
- return {
- ...actual,
- tracer: { startSpan: mocks.startSpan },
- };
-});
-
-vi.mock('@/server/modules/ModelRuntime', () => ({
- initModelRuntimeFromDB: vi.fn(),
-}));
-
-describe('ServerLLMTransport', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-07-23T00:00:00.000Z'));
- vi.clearAllMocks();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('records time to first chunk immediately even when the call never completes', () => {
- const transport = new ServerLLMTransport({
- operationId: 'operation-1',
- stepIndex: 2,
- streamManager: {},
- } as RuntimeExecutorContext);
- const trace = transport.createTrace({
- assistantMessageId: 'message-1',
- model: 'test-model',
- provider: 'test-provider',
- } satisfies LLMTraceInput);
-
- vi.advanceTimersByTime(1250);
- trace.onFirstChunk();
- trace.onFirstChunk();
-
- expect(mocks.chatSpan.setAttribute).toHaveBeenCalledOnce();
- expect(mocks.chatSpan.setAttribute).toHaveBeenCalledWith(
- ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,
- 1.25,
- );
- expect(mocks.chatSpan.addEvent).toHaveBeenCalledOnce();
- expect(mocks.chatSpan.addEvent).toHaveBeenCalledWith('gen_ai.first_chunk', {
- [ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK]: 1.25,
- });
- });
-});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
index 80357a47eb7..a20272320b7 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
@@ -26,7 +26,6 @@ import {
trace as otelTrace,
} from '@lobechat/observability-otel/api';
import {
- ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,
buildChatRequestAttributes,
buildChatResponseAttributes,
chatSpanName,
@@ -38,11 +37,6 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import type { RuntimeExecutorContext } from '../context';
import { log, sleep } from '../executorHelpers';
import { classifyLLMError } from '../llmErrorClassification';
-import {
- AGENT_STEP_TIMEOUT_ERROR_TYPE,
- getAgentStepAbortReason,
- raceWithAgentStepSignal,
-} from '../stepDeadline';
import { createServerCallLlmAttempt } from './serverCallLlmAttempt';
const getErrorMessage = (error: unknown): string => {
@@ -63,14 +57,6 @@ class ServerLLMRetryPolicy implements LLMRetryPolicy {
constructor(private readonly ctx: RuntimeExecutorContext) {}
classifyError(error: unknown) {
- if (this.ctx.signal?.aborted) {
- return {
- code: AGENT_STEP_TIMEOUT_ERROR_TYPE,
- kind: 'stop' as const,
- message: getAgentStepAbortReason(this.ctx.signal).message,
- };
- }
-
return classifyLLMError(error);
}
@@ -98,14 +84,12 @@ class ServerLLMRetryPolicy implements LLMRetryPolicy {
}
resolveRetryBudget(provider: string) {
- if (this.ctx.signal?.aborted) return 0;
-
return resolveLLMRetryBudget(provider, SERVER_LLM_RETRY_POLICY);
}
- waitForRetry = async (delayMs: number): Promise<void> => {
- await raceWithAgentStepSignal(sleep(delayMs), this.ctx.signal);
- };
+ async waitForRetry(delayMs: number): Promise<void> {
+ await sleep(delayMs);
+ }
}
class ServerLLMTrace implements LLMTrace {
@@ -154,11 +138,6 @@ class ServerLLMTrace implements LLMTrace {
onFirstChunk() {
if (this.firstChunkAt === undefined) {
this.firstChunkAt = Date.now() - this.llmStartTime;
- const timeToFirstChunkSeconds = this.firstChunkAt / 1000;
- this.chatSpan.setAttribute(ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, timeToFirstChunkSeconds);
- this.chatSpan.addEvent('gen_ai.first_chunk', {
- [ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK]: timeToFirstChunkSeconds,
- });
}
}
@@ -207,11 +186,7 @@ export class ServerLLMTransport implements LLMTransport {
}
async runAttempt(input: LLMAttemptInput): Promise<LLMAttemptExecution> {
- this.ctx.onStage?.('model.initialize');
- const modelRuntime = await raceWithAgentStepSignal(
- this.getModelRuntime(input.provider),
- this.ctx.signal,
- );
+ const modelRuntime = await this.getModelRuntime(input.provider);
return this.runAttemptWithRuntime(input, modelRuntime);
}
@@ -219,39 +194,30 @@ export class ServerLLMTransport implements LLMTransport {
payload: LLMStreamPayload,
handlers?: Parameters<LLMTransport['stream']>[1],
): Promise<LLMStreamResult> {
- this.ctx.onStage?.('model.initialize');
- const runtime = await raceWithAgentStepSignal(
- this.createModelRuntime(payload.provider),
- this.ctx.signal,
- );
+ const runtime = await this.createModelRuntime(payload.provider);
const { provider: _provider, ...runtimePayload } = payload;
let content = '';
let usage: LLMStreamResult['usage'];
let streamError: unknown;
- this.ctx.onStage?.('model.call');
- const response = await raceWithAgentStepSignal(
- runtime.chat(runtimePayload as any, {
- callback: {
- onCompletion: async (data: any) => {
- if (data.usage) usage = data.usage;
- },
- onError: async (errorData: unknown) => {
- streamError = errorData;
- handlers?.onError?.(errorData);
- },
- onText: async (text: string) => {
- content += text;
- handlers?.onText?.(text);
- },
+ const response = await runtime.chat(runtimePayload as any, {
+ callback: {
+ onCompletion: async (data: any) => {
+ if (data.usage) usage = data.usage;
},
- signal: this.ctx.signal,
- user: this.ctx.userId,
- }),
- this.ctx.signal,
- );
+ onError: async (errorData: unknown) => {
+ streamError = errorData;
+ handlers?.onError?.(errorData);
+ },
+ onText: async (text: string) => {
+ content += text;
+ handlers?.onText?.(text);
+ },
+ },
+ user: this.ctx.userId,
+ });
- await raceWithAgentStepSignal(consumeStreamUntilDone(response), this.ctx.signal);
+ await consumeStreamUntilDone(response);
if (streamError) {
throw new Error(getErrorMessage(streamError));
@@ -299,7 +265,6 @@ export class ServerLLMTransport implements LLMTransport {
}),
};
const operationLogId = `${this.ctx.operationId}:${this.ctx.stepIndex}`;
- this.ctx.onStage?.('model.call');
const attempt = createServerCallLlmAttempt({
attempt: input.attempt,
blobStore: this.blobStore,
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.test.ts
deleted file mode 100644
index ae7b46d6db0..00000000000
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.test.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-import type { ToolRunContext } from '@lobechat/agent-runtime';
-import type * as AgentRuntimeObservability from '@lobechat/observability-otel/modules/agent-runtime';
-import {
- ATTR_LOBEHUB_TOOL_EXECUTION_TARGET,
- ATTR_LOBEHUB_TOOL_TIMEOUT_MS,
-} from '@lobechat/observability-otel/modules/agent-runtime';
-import type { ChatToolPayload } from '@lobechat/types';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { RuntimeExecutorContext } from '../context';
-import type * as ExecutorHelpers from '../executorHelpers';
-import { ServerToolTransport } from './ServerToolTransport';
-
-const mocks = vi.hoisted(() => {
- const executeToolSpan = {
- addEvent: vi.fn(),
- end: vi.fn(),
- recordException: vi.fn(),
- setAttributes: vi.fn(),
- setStatus: vi.fn(),
- };
-
- return {
- archiveRuntimeToolResult: vi.fn(async (result) => result),
- dispatchClientTool: vi.fn(),
- executeToolSpan,
- resolveToolTimeoutMs: vi.fn(() => 4321),
- startSpan: vi.fn(() => executeToolSpan),
- };
-});
-
-vi.mock('@lobechat/observability-otel/modules/agent-runtime', async (importOriginal) => {
- const actual = await importOriginal<typeof AgentRuntimeObservability>();
-
- return {
- ...actual,
- tracer: { startSpan: mocks.startSpan },
- };
-});
-
-vi.mock('../dispatchClientTool', () => ({
- dispatchClientTool: mocks.dispatchClientTool,
-}));
-
-vi.mock('../executorHelpers', async (importOriginal) => {
- const actual = await importOriginal<typeof ExecutorHelpers>();
-
- return {
- ...actual,
- archiveRuntimeToolResult: mocks.archiveRuntimeToolResult,
- };
-});
-
-vi.mock('../resolveToolTimeout', () => ({
- resolveToolTimeoutMs: mocks.resolveToolTimeoutMs,
-}));
-
-describe('ServerToolTransport', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mocks.dispatchClientTool.mockResolvedValue({
- content: 'result',
- executionTime: 12,
- success: true,
- });
- });
-
- it('records the client target, effective timeout, execution completion, and blocking stages', async () => {
- const onStage = vi.fn();
- const hookDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
- const transport = new ServerToolTransport({
- hookDispatcher,
- onStage,
- operationId: 'operation-1',
- serverDB: {},
- stepIndex: 2,
- streamManager: { sendToolExecute: vi.fn() },
- toolExecutionService: {},
- userId: 'user-1',
- } as unknown as RuntimeExecutorContext);
- const payload = {
- apiName: 'search',
- executor: 'client',
- id: 'call-1',
- identifier: 'workspace',
- } as ChatToolPayload;
- const context = {
- callIndex: 0,
- effectiveManifestMap: {},
- parentMessageId: 'assistant-message-1',
- parsedArgs: { query: 'docs' },
- state: { metadata: {} },
- toolMessageId: 'tool-message-1',
- toolName: 'search',
- toolResultMaxLength: 1000,
- toolSource: 'builtin',
- } as unknown as ToolRunContext;
-
- await transport.run(payload, context);
-
- expect(onStage.mock.calls.map(([stage]) => stage)).toEqual([
- 'hook.before_tool',
- 'tool.client.wait',
- 'tool.result.archive',
- ]);
- expect(mocks.executeToolSpan.setAttributes).toHaveBeenCalledWith({
- [ATTR_LOBEHUB_TOOL_EXECUTION_TARGET]: 'client',
- [ATTR_LOBEHUB_TOOL_TIMEOUT_MS]: 4321,
- });
- expect(mocks.executeToolSpan.addEvent).toHaveBeenCalledWith('tool.execute.complete', {
- 'lobehub.tool.attempts': 1,
- });
- });
-
- it('does not report a deferred tool dispatch as execution complete', async () => {
- mocks.dispatchClientTool.mockResolvedValue({
- content: 'pending',
- deferred: true,
- executionTime: 12,
- success: true,
- });
- const transport = new ServerToolTransport({
- operationId: 'operation-1',
- serverDB: {},
- stepIndex: 2,
- streamManager: { sendToolExecute: vi.fn() },
- toolExecutionService: {},
- userId: 'user-1',
- } as unknown as RuntimeExecutorContext);
-
- await transport.run(
- {
- apiName: 'call',
- executor: 'client',
- id: 'call-1',
- identifier: 'async-tool',
- } as ChatToolPayload,
- {
- callIndex: 0,
- effectiveManifestMap: {},
- parentMessageId: 'assistant-message-1',
- parsedArgs: {},
- state: { metadata: {} },
- toolMessageId: 'tool-message-1',
- toolName: 'call',
- toolResultMaxLength: 1000,
- toolSource: 'builtin',
- } as unknown as ToolRunContext,
- );
-
- expect(mocks.executeToolSpan.addEvent).not.toHaveBeenCalledWith(
- 'tool.execute.complete',
- expect.anything(),
- );
- });
-});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index a9453ebc348..c92a4e76bde 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -8,9 +8,6 @@ import type {
import { executeToolWithRetry } from '@lobechat/agent-runtime';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import {
- ATTR_LOBEHUB_TOOL_ATTEMPTS,
- ATTR_LOBEHUB_TOOL_EXECUTION_TARGET,
- ATTR_LOBEHUB_TOOL_TIMEOUT_MS,
buildExecuteToolAttributes,
buildExecuteToolResultAttributes,
executeToolSpanName,
@@ -42,7 +39,6 @@ import {
import { resolveRunActiveDeviceId } from '../executors/resolveRunActiveDeviceId';
import { resolveRunProjectSkills } from '../executors/resolveRunProjectSkills';
import { resolveToolTimeoutMs } from '../resolveToolTimeout';
-import { raceWithAgentStepSignal, throwIfAgentStepAborted } from '../stepDeadline';
export class ServerToolTransport implements ToolTransport {
maxRetries = TOOL_MAX_RETRIES;
@@ -120,8 +116,6 @@ export class ServerToolTransport implements ToolTransport {
});
try {
- throwIfAgentStepAborted(this.ctx.signal);
- if (this.ctx.hookDispatcher) this.ctx.onStage?.('hook.before_tool');
const hookResult = await this.dispatchBeforeToolCall(chatToolPayload, context);
let toolCallMocked = false;
@@ -155,27 +149,19 @@ export class ServerToolTransport implements ToolTransport {
typeof streamManager.sendToolExecute === 'function'
) {
log(`[${operationLogId}] Dispatching tool ${context.toolName} to client via Agent Gateway`);
- this.ctx.onStage?.('tool.client.wait');
const timeoutMs = resolveToolTimeoutMs({
apiName: chatToolPayload.apiName,
args: context.parsedArgs,
- deadlineAt: this.ctx.deadlineAt,
manifest: context.effectiveManifestMap[chatToolPayload.identifier],
});
- executeToolSpan.setAttributes({
- [ATTR_LOBEHUB_TOOL_EXECUTION_TARGET]: 'client',
- [ATTR_LOBEHUB_TOOL_TIMEOUT_MS]: timeoutMs,
- });
const dispatchResult = await dispatchClientTool(chatToolPayload, {
agentId: context.state.metadata?.agentId,
assistantMessageId: context.parentMessageId,
documentId: context.state.metadata?.documentId,
- deadlineAt: this.ctx.deadlineAt,
groupId: context.state.metadata?.groupId,
operationId,
rootOperationId: operationId,
scope: context.state.metadata?.scope,
- signal: this.ctx.signal,
sourceMessageId: context.state.metadata?.sourceMessageId,
streamManager,
taskId: context.state.metadata?.taskId,
@@ -192,83 +178,64 @@ export class ServerToolTransport implements ToolTransport {
const timeoutMs = resolveToolTimeoutMs({
apiName: chatToolPayload.apiName,
args: context.parsedArgs,
- deadlineAt: this.ctx.deadlineAt,
manifest: context.effectiveManifestMap[chatToolPayload.identifier],
});
const agentVisibility = await this.resolveAgentVisibility(context);
- const executionTarget =
- isDeviceToolIdentifier(chatToolPayload.identifier) ||
- Boolean(context.state.metadata?.activeDeviceId)
- ? 'device'
- : 'server';
log(`[${operationLogId}] Executing tool ${context.toolName} ...`);
- this.ctx.onStage?.(
- executionTarget === 'device' ? 'tool.device.execute' : 'tool.server.execute',
- );
- executeToolSpan.setAttributes({
- [ATTR_LOBEHUB_TOOL_EXECUTION_TARGET]: executionTarget,
- [ATTR_LOBEHUB_TOOL_TIMEOUT_MS]: timeoutMs,
- });
execution = await executeToolWithRetry(
() =>
- raceWithAgentStepSignal(
- toolExecutionService.executeTool(chatToolPayload, {
- activatedSkills: context.activatedSkills as any,
- activeDeviceId: resolveRunActiveDeviceId(context.state.metadata),
- activeDeviceScope: context.state.metadata?.activeDeviceScope,
- agentId: context.state.metadata?.agentId,
- agentMember: buildServerAgentMemberRunner(
- this.ctx,
- context.state,
- chatToolPayload,
- context.parentMessageId,
- ),
- ...(agentVisibility !== undefined && { agentVisibility }),
- // Assistant message owning this tool call (β‰  source user message).
- assistantMessageId: context.parentMessageId,
- deadlineAt: this.ctx.deadlineAt,
- deviceCapable: context.state.metadata?.executionPlan
- ? isDeviceCapablePlan(context.state.metadata.executionPlan)
- : undefined,
- documentId: context.state.metadata?.documentId,
- editingAgentId: context.state.metadata?.editingAgentId,
- execSubAgent: this.ctx.execSubAgent,
- executionTimeoutMs: timeoutMs,
- groupId: context.state.metadata?.groupId,
- isSubAgent: context.state.metadata?.isSubAgent === true,
- memoryToolPermission:
- context.state.metadata?.agentConfig?.chatConfig?.memory?.toolPermission,
- messageId: context.state.metadata?.sourceMessageId,
- operationId,
- projectSkills: resolveRunProjectSkills(context.state.metadata),
- rootOperationId: operationId,
- scope: context.state.metadata?.scope,
- serverDB,
- signal: this.ctx.signal,
- skipResultTruncation: true,
- subAgent: buildServerVirtualSubAgentRunner(
- this.ctx,
- context.state,
- chatToolPayload,
- context.parentMessageId,
- ),
- taskId: context.state.metadata?.taskId,
- threadId: context.state.metadata?.threadId,
- toolCallId: chatToolPayload.id,
- toolManifestMap: context.effectiveManifestMap,
- toolMessageId: context.toolMessageId,
- toolResultMaxLength: context.toolResultMaxLength,
- topicId: this.ctx.topicId,
- userId,
- workingDirectory: context.state.metadata?.deviceSystemInfo?.workingDirectory,
- workspaceId: context.state.metadata?.workspaceId ?? this.ctx.workspaceId,
- }),
- this.ctx.signal,
- ),
+ toolExecutionService.executeTool(chatToolPayload, {
+ activatedSkills: context.activatedSkills as any,
+ activeDeviceId: resolveRunActiveDeviceId(context.state.metadata),
+ activeDeviceScope: context.state.metadata?.activeDeviceScope,
+ agentId: context.state.metadata?.agentId,
+ agentMember: buildServerAgentMemberRunner(
+ this.ctx,
+ context.state,
+ chatToolPayload,
+ context.parentMessageId,
+ ),
+ ...(agentVisibility !== undefined && { agentVisibility }),
+ // Assistant message owning this tool call (β‰  source user message).
+ assistantMessageId: context.parentMessageId,
+ deviceCapable: context.state.metadata?.executionPlan
+ ? isDeviceCapablePlan(context.state.metadata.executionPlan)
+ : undefined,
+ documentId: context.state.metadata?.documentId,
+ editingAgentId: context.state.metadata?.editingAgentId,
+ execSubAgent: this.ctx.execSubAgent,
+ executionTimeoutMs: timeoutMs,
+ groupId: context.state.metadata?.groupId,
+ isSubAgent: context.state.metadata?.isSubAgent === true,
+ memoryToolPermission:
+ context.state.metadata?.agentConfig?.chatConfig?.memory?.toolPermission,
+ messageId: context.state.metadata?.sourceMessageId,
+ operationId,
+ projectSkills: resolveRunProjectSkills(context.state.metadata),
+ rootOperationId: operationId,
+ scope: context.state.metadata?.scope,
+ serverDB,
+ skipResultTruncation: true,
+ subAgent: buildServerVirtualSubAgentRunner(
+ this.ctx,
+ context.state,
+ chatToolPayload,
+ context.parentMessageId,
+ ),
+ taskId: context.state.metadata?.taskId,
+ threadId: context.state.metadata?.threadId,
+ toolCallId: chatToolPayload.id,
+ toolManifestMap: context.effectiveManifestMap,
+ toolMessageId: context.toolMessageId,
+ toolResultMaxLength: context.toolResultMaxLength,
+ topicId: this.ctx.topicId,
+ userId,
+ workingDirectory: context.state.metadata?.deviceSystemInfo?.workingDirectory,
+ workspaceId: context.state.metadata?.workspaceId ?? this.ctx.workspaceId,
+ }),
{
- isInterrupted: () =>
- this.ctx.signal?.aborted ? Promise.resolve(true) : isOperationInterrupted(this.ctx),
+ isInterrupted: () => isOperationInterrupted(this.ctx),
maxRetries: TOOL_MAX_RETRIES,
onRetry: ({ attempt, kind, maxAttempts }) =>
log(
@@ -283,13 +250,6 @@ export class ServerToolTransport implements ToolTransport {
);
}
- if (!execution.result.deferred) {
- executeToolSpan.addEvent('tool.execute.complete', {
- [ATTR_LOBEHUB_TOOL_ATTEMPTS]: execution.attempts,
- });
- }
- throwIfAgentStepAborted(this.ctx.signal);
-
if (execution.result.deferred) {
executeToolSpan.setAttributes(
buildExecuteToolResultAttributes({ attempts: execution.attempts, success: true }),
@@ -301,7 +261,6 @@ export class ServerToolTransport implements ToolTransport {
...execution.result,
executionTime: execution.result.executionTime ?? 0,
};
- this.ctx.onStage?.('tool.result.archive');
const executionResult = await archiveRuntimeToolResult(resultWithExecutionTime, {
agentId: context.state.metadata?.agentId,
identifier: chatToolPayload.identifier,
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
index 83dc3f76ec8..35d839929bf 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
@@ -4,7 +4,6 @@ import type { ChatMethodOptions, ModelRuntime } from '@lobechat/model-runtime';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { RuntimeExecutorContext } from '../context';
-import { AgentStepTimeoutError } from '../stepDeadline';
import { createServerCallLlmAttempt } from './serverCallLlmAttempt';
import type { ServerCallLlmTooling } from './serverCallLlmTooling';
@@ -44,7 +43,6 @@ const createAttempt = (
runCallbacks: (options: ChatMethodOptions) => Promise<void>,
blobStore?: BlobStore,
attemptOverrides?: { clientIp?: string; userAgent?: string },
- contextOverrides?: Partial<RuntimeExecutorContext>,
) => {
const publishStreamChunk = vi.fn().mockResolvedValue('event-1');
const streamManager = {
@@ -59,7 +57,6 @@ const createAttempt = (
streamManager,
toolExecutionService: {} as RuntimeExecutorContext['toolExecutionService'],
userId: 'user-1',
- ...contextOverrides,
} satisfies RuntimeExecutorContext;
const chat = vi.fn(async (_payload, options?: ChatMethodOptions) => {
await runCallbacks(options!);
@@ -158,23 +155,6 @@ describe('ServerCallLlmAttempt', () => {
);
});
- it('reports model finalization after the response stream is consumed', async () => {
- const onStage = vi.fn();
- const { attempt } = createAttempt(
- async ({ callback }) => {
- await callback?.onText?.('Answer');
- await callback?.onCompletion?.({ text: '', usage: { totalOutputTokens: 1 } });
- },
- undefined,
- undefined,
- { onStage },
- );
-
- await attempt.execute();
-
- expect(onStage).toHaveBeenCalledWith('model.finalize');
- });
-
it('forwards clientIp / userAgent into the chat call metadata when provided', async () => {
const { attempt, chat } = createAttempt(
async ({ callback }) => {
@@ -214,24 +194,6 @@ describe('ServerCallLlmAttempt', () => {
expect(metadata.userAgent).toBeUndefined();
});
- it('passes the step signal to model-runtime and rejects promptly when it aborts', async () => {
- const controller = new AbortController();
- const { attempt, chat } = createAttempt(() => new Promise(() => {}), undefined, undefined, {
- signal: controller.signal,
- });
- const executionPromise = attempt.execute();
- await vi.waitFor(() => expect(chat).toHaveBeenCalled());
- expect(chat.mock.calls[0][1]?.signal).toBe(controller.signal);
- const timeoutError = new AgentStepTimeoutError({
- deadlineAt: Date.now(),
- stage: 'model.call',
- });
-
- controller.abort(timeoutError);
-
- await expect(executionPromise).rejects.toBe(timeoutError);
- });
-
it('keeps partial output and usage readable after a stream error', async () => {
const { attempt } = createAttempt(async ({ callback }) => {
await callback?.onText?.('Partial answer');
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
index 053d8da29fb..7df19e6a15b 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
@@ -18,7 +18,6 @@ import { pickString, toRecord } from '@lobechat/utils/object';
import type { RuntimeExecutorContext } from '../context';
import { isOperationInterrupted, log, timing } from '../executorHelpers';
-import { raceWithAgentStepSignal, throwIfAgentStepAborted } from '../stepDeadline';
import {
createServerCallLlmStreamSink,
type ServerCallLlmStreamSink,
@@ -142,112 +141,105 @@ export class ServerCallLlmAttempt {
this.chatPayload.tools?.length ?? 0,
);
- throwIfAgentStepAborted(this.ctx.signal);
- const response = await raceWithAgentStepSignal(
- this.modelRuntime.chat(this.chatPayload, {
- callback: {
- onBase64Image: async ({ image }) => {
- this.onFirstChunk();
- await this.streamSink.appendBase64Image(image);
- },
- onCompletion: async (data) => {
- if (data.usage) this.usage = data.usage;
- if (data.speed) this.speed = data.speed;
- if (data.finishReason) this.finishReason = data.finishReason;
- },
- onContentPart: async (part) => {
- this.onFirstChunk();
- await this.streamSink.appendContentPart(part);
- },
- onError: async (errorData) => {
- this.streamError = errorData;
- console.error(`[${this.operationLogId}][stream_error]`, errorData);
- },
- onGrounding: async (groundingData) => {
- log(`[${this.operationLogId}][grounding] %O`, groundingData);
- this.grounding = groundingData;
+ const response = await this.modelRuntime.chat(this.chatPayload, {
+ callback: {
+ onBase64Image: async ({ image }) => {
+ this.onFirstChunk();
+ await this.streamSink.appendBase64Image(image);
+ },
+ onCompletion: async (data) => {
+ if (data.usage) this.usage = data.usage;
+ if (data.speed) this.speed = data.speed;
+ if (data.finishReason) this.finishReason = data.finishReason;
+ },
+ onContentPart: async (part) => {
+ this.onFirstChunk();
+ await this.streamSink.appendContentPart(part);
+ },
+ onError: async (errorData) => {
+ this.streamError = errorData;
+ console.error(`[${this.operationLogId}][stream_error]`, errorData);
+ },
+ onGrounding: async (groundingData) => {
+ log(`[${this.operationLogId}][grounding] %O`, groundingData);
+ this.grounding = groundingData;
- await this.ctx.streamManager.publishStreamChunk(
- this.ctx.operationId,
- this.ctx.stepIndex,
- {
- chunkType: 'grounding',
- grounding: groundingData,
- },
- );
- },
- onReasoningPart: async (part) => {
- this.onFirstChunk();
- await this.streamSink.appendReasoningPart(part);
- },
- onText: async (text) => {
- this.onFirstChunk();
- timing(
- '[%s] onText received chunk at %d, length: %d',
- this.operationLogId,
- Date.now(),
- text.length,
- );
- await this.streamSink.appendText(text);
- },
- onThinking: async (reasoning) => {
- this.onFirstChunk();
- timing(
- '[%s] onThinking received chunk at %d, length: %d',
- this.operationLogId,
- Date.now(),
- reasoning.length,
- );
- await this.streamSink.appendThinking(reasoning);
- },
- onToolsCalling: async ({ toolsCalling: raw }) => {
- const resolvedCalls = new ToolNameResolver().resolve(
- raw,
- this.resolved.promptManifestMap,
- this.resolved.tools.map((tool) => tool.function.name),
- );
- const payload = resolvedCalls.map((toolCall) => ({
- ...toolCall,
- executor: this.resolved.executorMap?.[toolCall.identifier],
- source: this.resolved.sourceMap[toolCall.identifier],
- }));
+ await this.ctx.streamManager.publishStreamChunk(
+ this.ctx.operationId,
+ this.ctx.stepIndex,
+ {
+ chunkType: 'grounding',
+ grounding: groundingData,
+ },
+ );
+ },
+ onReasoningPart: async (part) => {
+ this.onFirstChunk();
+ await this.streamSink.appendReasoningPart(part);
+ },
+ onText: async (text) => {
+ this.onFirstChunk();
+ timing(
+ '[%s] onText received chunk at %d, length: %d',
+ this.operationLogId,
+ Date.now(),
+ text.length,
+ );
+ await this.streamSink.appendText(text);
+ },
+ onThinking: async (reasoning) => {
+ this.onFirstChunk();
+ timing(
+ '[%s] onThinking received chunk at %d, length: %d',
+ this.operationLogId,
+ Date.now(),
+ reasoning.length,
+ );
+ await this.streamSink.appendThinking(reasoning);
+ },
+ onToolsCalling: async ({ toolsCalling: raw }) => {
+ const resolvedCalls = new ToolNameResolver().resolve(
+ raw,
+ this.resolved.promptManifestMap,
+ this.resolved.tools.map((tool) => tool.function.name),
+ );
+ const payload = resolvedCalls.map((toolCall) => ({
+ ...toolCall,
+ executor: this.resolved.executorMap?.[toolCall.identifier],
+ source: this.resolved.sourceMap[toolCall.identifier],
+ }));
- this.toolsCalling = payload;
- // Keep raw arguments through execution so malformed JSON can reach the
- // tool error path and give the model a self-repair signal. Finalizers
- // sanitize only the persisted DB and replay-state copies.
- this.toolCalls = raw;
+ this.toolsCalling = payload;
+ // Keep raw arguments through execution so malformed JSON can reach the
+ // tool error path and give the model a self-repair signal. Finalizers
+ // sanitize only the persisted DB and replay-state copies.
+ this.toolCalls = raw;
- await this.streamSink.flushTextBuffer();
- await this.ctx.streamManager.publishStreamChunk(
- this.ctx.operationId,
- this.ctx.stepIndex,
- {
- chunkType: 'tools_calling',
- toolsCalling: payload,
- },
- );
- },
- },
- metadata: {
- clientIp: this.clientIp,
- operationId: this.ctx.operationId,
- topicId: this.topicId,
- trigger: this.trigger,
- userAgent: this.userAgent,
+ await this.streamSink.flushTextBuffer();
+ await this.ctx.streamManager.publishStreamChunk(
+ this.ctx.operationId,
+ this.ctx.stepIndex,
+ {
+ chunkType: 'tools_calling',
+ toolsCalling: payload,
+ },
+ );
},
- signal: this.ctx.signal,
- user: this.ctx.userId,
- }),
- this.ctx.signal,
- );
+ },
+ metadata: {
+ clientIp: this.clientIp,
+ operationId: this.ctx.operationId,
+ topicId: this.topicId,
+ trigger: this.trigger,
+ userAgent: this.userAgent,
+ },
+ user: this.ctx.userId,
+ });
- await raceWithAgentStepSignal(consumeStreamUntilDone(response), this.ctx.signal);
- throwIfAgentStepAborted(this.ctx.signal);
+ await consumeStreamUntilDone(response);
if (this.streamError) throw createStreamExecutionError(this.streamError);
- this.ctx.onStage?.('model.finalize');
await this.streamSink.flushTextBuffer();
await this.streamSink.flushReasoningBuffer();
this.streamSink.clearBuffers();
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index 67d4fe17671..8ed6ba0cd8d 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -29,8 +29,6 @@ export interface RuntimeExecutorContext {
allowEarlyFinalAnswerVisibleOutputEnd?: boolean;
botContext?: unknown;
botPlatformContext?: BotPlatformContext;
- /** Absolute wall-clock deadline for the current delivered step. */
- deadlineAt?: number;
discordContext?: any;
evalContext?: EvalContext;
/**
@@ -54,12 +52,8 @@ export interface RuntimeExecutorContext {
hookDispatcher?: HookDispatcher;
loadAgentState?: (operationId: string) => Promise<AgentState | null>;
messageModel: MessageModel;
- /** Reports long-running model and tool stages to the step handler. */
- onStage?: (stage: string) => void;
operationId: string;
serverDB: LobeChatDatabase;
- /** Cooperative cancellation shared by all work within the current step. */
- signal?: AbortSignal;
stepIndex: number;
stream?: boolean;
streamManager: IStreamEventManager;
diff --git a/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts b/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts
index 4e0f3ac136f..1a21137f90f 100644
--- a/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts
+++ b/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts
@@ -5,11 +5,6 @@ import type { ToolExecutionResultResponse } from '@/server/services/toolExecutio
import { getAgentRuntimeRedisClient } from './redis';
import { GLOBAL_DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, MIN_TIMEOUT_MS } from './resolveToolTimeout';
-import {
- getAgentStepAbortReason,
- raceWithAgentStepSignal,
- throwIfAgentStepAborted,
-} from './stepDeadline';
import type { ToolResultPayload } from './ToolResultWaiter';
import { ToolResultWaiter } from './ToolResultWaiter';
import type { IStreamEventManager } from './types';
@@ -20,15 +15,11 @@ interface DispatchContext {
agentId?: string | null;
/** Assistant message that carries this tool call. */
assistantMessageId?: string;
- /** Absolute deadline of the containing step. */
- deadlineAt?: number;
documentId?: string | null;
groupId?: string | null;
operationId: string;
rootOperationId?: string;
scope?: string | null;
- /** Cooperative cancellation inherited from the containing step. */
- signal?: AbortSignal;
sourceMessageId?: string | null;
streamManager: IStreamEventManager;
taskId?: string | null;
@@ -36,21 +27,16 @@ interface DispatchContext {
/**
* Per-call execution budget in milliseconds, normally produced by
* `resolveToolTimeoutMs`. When omitted, falls back to the global default
- * (`GLOBAL_DEFAULT_TIMEOUT_MS`). Configuration is clamped to
- * `[MIN_TIMEOUT_MS, MAX_TIMEOUT_MS]`, then reduced to the containing step's
- * remaining budget when necessary.
+ * (`GLOBAL_DEFAULT_TIMEOUT_MS`). Always clamped to
+ * `[MIN_TIMEOUT_MS, MAX_TIMEOUT_MS]` regardless of source β€” the client is
+ * a suggester, this dispatcher is the arbiter.
*/
timeoutMs?: number;
topicId?: string | null;
}
-const clampTimeout = (value: number, deadlineAt?: number): number => {
- const configuredTimeout = Math.min(Math.max(Math.trunc(value), MIN_TIMEOUT_MS), MAX_TIMEOUT_MS);
-
- if (deadlineAt === undefined) return configuredTimeout;
-
- return Math.min(configuredTimeout, Math.max(1, Math.trunc(deadlineAt - Date.now())));
-};
+const clampTimeout = (value: number): number =>
+ Math.min(Math.max(Math.trunc(value), MIN_TIMEOUT_MS), MAX_TIMEOUT_MS);
const buildTimeoutResult = (executionTime: number): ToolExecutionResultResponse => ({
content: '',
@@ -88,8 +74,6 @@ export async function dispatchClientTool(
const { operationId, streamManager } = ctx;
const startedAt = Date.now();
- throwIfAgentStepAborted(ctx.signal);
-
if (typeof streamManager.sendToolExecute !== 'function') {
return buildErrorResult(
0,
@@ -112,7 +96,7 @@ export async function dispatchClientTool(
const blockingClient = redis.duplicate();
const waiter = new ToolResultWaiter(blockingClient, redis);
- const timeoutMs = clampTimeout(ctx.timeoutMs ?? GLOBAL_DEFAULT_TIMEOUT_MS, ctx.deadlineAt);
+ const timeoutMs = clampTimeout(ctx.timeoutMs ?? GLOBAL_DEFAULT_TIMEOUT_MS);
try {
log(
@@ -124,31 +108,25 @@ export async function dispatchClientTool(
timeoutMs,
);
- await raceWithAgentStepSignal(
- streamManager.sendToolExecute(operationId, {
- agentId: ctx.agentId,
- apiName: chatToolPayload.apiName,
- arguments: chatToolPayload.arguments,
- assistantMessageId: ctx.assistantMessageId,
- documentId: ctx.documentId,
- executionTimeoutMs: timeoutMs,
- groupId: ctx.groupId,
- identifier: chatToolPayload.identifier,
- rootOperationId: ctx.rootOperationId ?? operationId,
- scope: ctx.scope,
- sourceMessageId: ctx.sourceMessageId,
- taskId: ctx.taskId,
- threadId: ctx.threadId,
- toolCallId: chatToolPayload.id,
- topicId: ctx.topicId,
- }),
- ctx.signal,
- );
-
- const result = await raceWithAgentStepSignal(
- waiter.waitForResult(chatToolPayload.id, timeoutMs),
- ctx.signal,
- );
+ await streamManager.sendToolExecute(operationId, {
+ agentId: ctx.agentId,
+ apiName: chatToolPayload.apiName,
+ arguments: chatToolPayload.arguments,
+ assistantMessageId: ctx.assistantMessageId,
+ documentId: ctx.documentId,
+ executionTimeoutMs: timeoutMs,
+ groupId: ctx.groupId,
+ identifier: chatToolPayload.identifier,
+ rootOperationId: ctx.rootOperationId ?? operationId,
+ scope: ctx.scope,
+ sourceMessageId: ctx.sourceMessageId,
+ taskId: ctx.taskId,
+ threadId: ctx.threadId,
+ toolCallId: chatToolPayload.id,
+ topicId: ctx.topicId,
+ });
+
+ const result = await waiter.waitForResult(chatToolPayload.id, timeoutMs);
const executionTime = Date.now() - startedAt;
if (!result) {
@@ -163,8 +141,6 @@ export async function dispatchClientTool(
return projectToExecutionResult(result, executionTime);
} catch (error) {
- if (ctx.signal?.aborted) throw getAgentStepAbortReason(ctx.signal);
-
const executionTime = Date.now() - startedAt;
log('[%s] client tool dispatch failed: %O', operationId, error);
return buildErrorResult(executionTime, error);
diff --git a/apps/server/src/modules/AgentRuntime/resolveToolTimeout.ts b/apps/server/src/modules/AgentRuntime/resolveToolTimeout.ts
index 7dec699d0cf..3ee9d4bea0e 100644
--- a/apps/server/src/modules/AgentRuntime/resolveToolTimeout.ts
+++ b/apps/server/src/modules/AgentRuntime/resolveToolTimeout.ts
@@ -1,6 +1,4 @@
-import type { LobeToolManifest } from '@lobechat/context-engine';
-
-import { DEFAULT_AGENT_STEP_DEADLINE_MS } from './stepDeadline';
+import { type LobeToolManifest } from '@lobechat/context-engine';
/**
* Global fallback when neither the LLM nor the tool manifest specifies a
@@ -16,10 +14,10 @@ export const MIN_TIMEOUT_MS = 1_000;
/**
* Hard ceiling enforced server-side regardless of what the LLM or manifest
- * asks for. A tool must leave enough room for the containing step to persist
- * its terminal state and release execution resources.
+ * asks for. Matches the cloud agent function window (800s) so a single
+ * client-tool dispatch never outlives its containing run.
*/
-export const MAX_TIMEOUT_MS = DEFAULT_AGENT_STEP_DEADLINE_MS;
+export const MAX_TIMEOUT_MS = 800_000;
const clamp = (value: number): number =>
Math.min(Math.max(Math.trunc(value), MIN_TIMEOUT_MS), MAX_TIMEOUT_MS);
@@ -37,8 +35,6 @@ export interface ResolveToolTimeoutInput {
* takes top priority when present.
*/
args?: Record<string, unknown> | null;
- /** Absolute deadline of the containing step. */
- deadlineAt?: number;
/** Manifest for the tool being dispatched, looked up by identifier. */
manifest?: LobeToolManifest;
}
@@ -51,23 +47,20 @@ export interface ResolveToolTimeoutInput {
* 2. `manifest.api[apiName].defaultTimeoutMs` β€” tool-author default (ms)
* 3. `GLOBAL_DEFAULT_TIMEOUT_MS` (120_000)
*
- * Configuration is clamped to `[MIN_TIMEOUT_MS, MAX_TIMEOUT_MS]`, then reduced
- * to the containing step's remaining budget when a deadline is present. The
+ * The result is always clamped to `[MIN_TIMEOUT_MS, MAX_TIMEOUT_MS]`. The
* client is a *suggester*; this function is the sole *arbiter*.
*/
export const resolveToolTimeoutMs = ({
apiName,
args,
- deadlineAt,
manifest,
}: ResolveToolTimeoutInput): number => {
const argTimeout = readPositiveNumber(args?.timeout);
- const manifestApi = manifest?.api?.find((item) => item.name === apiName);
- const manifestDefault = readPositiveNumber(manifestApi?.defaultTimeoutMs);
- const configuredTimeout = clamp(argTimeout ?? manifestDefault ?? GLOBAL_DEFAULT_TIMEOUT_MS);
+ if (argTimeout !== undefined) return clamp(argTimeout);
- if (deadlineAt === undefined) return configuredTimeout;
+ const manifestApi = manifest?.api?.find((a) => a.name === apiName);
+ const manifestDefault = readPositiveNumber(manifestApi?.defaultTimeoutMs);
+ if (manifestDefault !== undefined) return clamp(manifestDefault);
- const remainingStepBudget = Math.max(1, Math.trunc(deadlineAt - Date.now()));
- return Math.min(configuredTimeout, remainingStepBudget);
+ return clamp(GLOBAL_DEFAULT_TIMEOUT_MS);
};
diff --git a/apps/server/src/modules/AgentRuntime/stepDeadline.ts b/apps/server/src/modules/AgentRuntime/stepDeadline.ts
deleted file mode 100644
index 066e9d8bbf3..00000000000
--- a/apps/server/src/modules/AgentRuntime/stepDeadline.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-export const AGENT_STEP_TIMEOUT_ERROR_TYPE = 'AgentStepTimeout';
-
-export const DEFAULT_AGENT_STEP_DEADLINE_MS = 8 * 60 * 1000;
-
-interface AgentStepTimeoutErrorOptions {
- deadlineAt: number;
- stage: string;
- stageElapsedMs?: number;
-}
-
-export class AgentStepTimeoutError extends Error {
- readonly deadlineAt: number;
- readonly errorType = AGENT_STEP_TIMEOUT_ERROR_TYPE;
- handled = false;
- readonly stage: string;
- readonly stageElapsedMs?: number;
-
- constructor({ deadlineAt, stage, stageElapsedMs }: AgentStepTimeoutErrorOptions) {
- super(`Agent step exceeded its deadline while in stage: ${stage}`);
- this.name = AGENT_STEP_TIMEOUT_ERROR_TYPE;
- this.deadlineAt = deadlineAt;
- this.stage = stage;
- this.stageElapsedMs = stageElapsedMs;
- }
-}
-
-export const isAgentStepTimeoutError = (error: unknown): error is AgentStepTimeoutError =>
- error instanceof AgentStepTimeoutError ||
- (typeof error === 'object' &&
- error !== null &&
- 'errorType' in error &&
- error.errorType === AGENT_STEP_TIMEOUT_ERROR_TYPE);
-
-export const markAgentStepTimeoutHandled = (error: AgentStepTimeoutError): void => {
- error.handled = true;
-};
-
-export const getAgentStepAbortReason = (signal: AbortSignal): Error => {
- if (signal.reason instanceof Error) return signal.reason;
-
- return new Error(typeof signal.reason === 'string' ? signal.reason : 'Agent step aborted');
-};
-
-/**
- * Preserve the exact abort reason instance rather than normalizing it through
- * agentRuntime/abort.ts. The timeout instance is marked as handled only after
- * its terminal state is durable, and the HTTP boundary reads that same marker
- * to choose between QStash ACK and retry.
- */
-export const throwIfAgentStepAborted = (signal?: AbortSignal): void => {
- if (!signal?.aborted) return;
-
- throw getAgentStepAbortReason(signal);
-};
-
-export const raceWithAgentStepSignal = async <T>(
- promise: PromiseLike<T> | T,
- signal?: AbortSignal,
-): Promise<T> => {
- const pending = Promise.resolve(promise);
- if (!signal) return pending;
-
- throwIfAgentStepAborted(signal);
-
- return new Promise<T>((resolve, reject) => {
- const handleAbort = () => reject(getAgentStepAbortReason(signal));
- signal.addEventListener('abort', handleAbort, { once: true });
-
- pending.then(resolve, reject).finally(() => {
- signal.removeEventListener('abort', handleAbort);
- });
- });
-};
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index ac7529f7ac6..94fdf54729e 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -7,11 +7,14 @@ import type { MockInstance } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentOperationModel } from '@/database/models/agentOperation';
-import { AgentStepTimeoutError } from '@/server/modules/AgentRuntime/stepDeadline';
import { AgentRuntimeService } from './AgentRuntimeService';
import { hookDispatcher } from './hooks';
-import type { AgentExecutionParams, OperationCreationParams, StartExecutionParams } from './types';
+import {
+ type AgentExecutionParams,
+ type OperationCreationParams,
+ type StartExecutionParams,
+} from './types';
vi.mock('@lobechat/model-runtime', () => ({
// RuntimeExecutors (loaded transitively) resolves extend params via this
@@ -585,70 +588,6 @@ describe('AgentRuntimeService', () => {
expect(mockQueueService.scheduleMessage).toHaveBeenCalled();
});
- it('should keep a committed done state when the deadline fires during saveStepResult', async () => {
- const controller = new AbortController();
- const timeoutError = new AgentStepTimeoutError({
- deadlineAt: Date.now(),
- stage: 'state.save',
- });
- const mockStepResult = {
- events: [],
- newState: { ...mockState, status: 'done', stepCount: 2 },
- nextContext: null,
- };
- const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };
- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });
- mockCoordinator.saveStepResult.mockImplementationOnce(async () => {
- controller.abort(timeoutError);
- });
-
- const result = await service.executeStep({
- ...mockParams,
- deadlineAt: timeoutError.deadlineAt,
- signal: controller.signal,
- });
-
- expect(result).toMatchObject({
- nextStepScheduled: false,
- state: { status: 'done' },
- success: true,
- });
- expect(timeoutError.handled).toBe(false);
- expect(mockCoordinator.saveAgentState).not.toHaveBeenCalledWith(
- 'test-operation-1',
- expect.objectContaining({ status: 'error' }),
- );
- expect(mockStreamManager.publishStreamEvent).not.toHaveBeenCalledWith(
- 'test-operation-1',
- expect.objectContaining({ type: 'error' }),
- );
- });
-
- it('should stop waiting when state loading stalls past the step deadline', async () => {
- const controller = new AbortController();
- const timeoutError = new AgentStepTimeoutError({
- deadlineAt: Date.now(),
- stage: 'state.load',
- });
- mockCoordinator.loadAgentState.mockImplementationOnce(() => new Promise(() => {}));
-
- const execution = service.executeStep({
- ...mockParams,
- deadlineAt: timeoutError.deadlineAt,
- signal: controller.signal,
- });
- await vi.waitFor(() => expect(mockCoordinator.loadAgentState).toHaveBeenCalled());
-
- controller.abort(timeoutError);
-
- await expect(execution).rejects.toBe(timeoutError);
- expect(timeoutError.handled).toBe(true);
- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(
- 'test-operation-1',
- expect.objectContaining({ status: 'error' }),
- );
- });
-
it('should resume async tools with the last pending tool result as parentMessageId', async () => {
const pendingTools = [
{
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 5c56b39a834..a94b056988b 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -51,12 +51,6 @@ import {
createRuntimeExecutors,
type RuntimeExecutorContext,
} from '@/server/modules/AgentRuntime/RuntimeExecutors';
-import {
- isAgentStepTimeoutError,
- markAgentStepTimeoutHandled,
- raceWithAgentStepSignal,
- throwIfAgentStepAborted,
-} from '@/server/modules/AgentRuntime/stepDeadline';
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
@@ -728,29 +722,21 @@ export class AgentRuntimeService {
*/
async executeStep(params: AgentExecutionParams): Promise<AgentExecutionResult> {
const {
- approvedToolCall,
- asyncToolVerifyAttempt,
+ operationId,
+ stepIndex,
context,
- deadlineAt,
- externalRetryCount = 0,
- finishAfterAsyncTool,
- groupMemberTimeout,
humanInput,
- onStage,
- operationId,
- rejectAndContinue,
+ approvedToolCall,
rejectionReason,
+ rejectAndContinue,
resumeAsyncTool,
- signal,
- stepIndex,
+ finishAfterAsyncTool,
+ groupMemberTimeout,
toolMessageId,
verifyAsyncToolBarrier,
+ asyncToolVerifyAttempt,
+ externalRetryCount = 0,
} = params;
- const reportStage = (stage: string) => onStage?.(stage);
- const awaitStepWork = <T>(promise: Promise<T>): Promise<T> =>
- raceWithAgentStepSignal(promise, signal);
-
- throwIfAgentStepAborted(signal);
// Group member timeout watchdog: enforce a member's deadline without claiming
// the step lock. No-op if the member already finished; otherwise interrupt it
@@ -786,7 +772,6 @@ export class AgentRuntimeService {
}
// ===== Distributed lock: prevent duplicate execution from QStash retries =====
- reportStage('lock.claim');
const stepLockOwner = createStepLockOwner(operationId, stepIndex);
const claimed = await this.coordinator.tryClaimStep(
operationId,
@@ -859,7 +844,6 @@ export class AgentRuntimeService {
try {
return await otelContext.with(invokeAgentCtx, async () => {
- throwIfAgentStepAborted(signal);
log('[%s][%d] Start step executing...', operationId, stepIndex);
// Load agent state BEFORE publishing step_start so we can attach the
@@ -868,27 +852,20 @@ export class AgentRuntimeService {
// the snapshot query here reflects strongly-consistent state β€” that's
// the contract that lets the client treat the pushed uiMessages as
// the source of truth instead of doing its own refetch.
- reportStage('state.load');
- const agentState = await awaitStepWork(this.coordinator.loadAgentState(operationId));
+ const agentState = await this.coordinator.loadAgentState(operationId);
if (!agentState) {
throw new Error(`Agent state not found for operation ${operationId}`);
}
- reportStage('messages.snapshot');
- const stepStartUiMessages = await awaitStepWork(
- this.queryUiMessages(agentState, { skipWorks: true }),
- );
- reportStage('gateway.publish_step_start');
- await awaitStepWork(
- this.streamManager.publishStreamEvent(operationId, {
- data: {
- ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }),
- },
- stepIndex,
- type: 'step_start',
- }),
- );
+ const stepStartUiMessages = await this.queryUiMessages(agentState, { skipWorks: true });
+ await this.streamManager.publishStreamEvent(operationId, {
+ data: {
+ ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }),
+ },
+ stepIndex,
+ type: 'step_start',
+ });
agentState.metadata = {
...agentState.metadata,
@@ -902,8 +879,7 @@ export class AgentRuntimeService {
// refresh below. With this in place the Redis-persisted state no longer
// needs to carry the (potentially multi-MB) `messages` array, which is
// what trips Upstash's 10MB single-request limit and drops the op.
- reportStage('messages.rehydrate');
- await awaitStepWork(this.rehydrateStateMessagesFromDB(agentState));
+ await this.rehydrateStateMessagesFromDB(agentState);
// Enrich invoke_agent span with agent identity now that state is loaded.
const stateAgentConfig = agentState.metadata?.agentConfig as
@@ -959,7 +935,6 @@ export class AgentRuntimeService {
const reason = this.determineCompletionReason(agentState);
- reportStage('completion.hooks');
await this.completionLifecycle.emitSignalEvents(operationId, agentState, reason);
// Dispatch completion hooks so consumers (e.g., bot local-mode promise) can finalize
@@ -977,46 +952,41 @@ export class AgentRuntimeService {
// Dispatch beforeStep hooks
try {
- reportStage('hook.before_step');
const beforeStepMetadata = agentState?.metadata || {};
- const beforeStepSignalEmission = await awaitStepWork(
- emitAgentSignalSourceEvent(
- {
- payload: {
- agentId: beforeStepMetadata?.agentId,
- operationId,
- serializedContext: undefined,
- stepIndex,
- topicId: beforeStepMetadata?.topicId,
- turnCount: agentState?.stepCount || 0,
- },
- sourceId: `${operationId}:before:${stepIndex}`,
- sourceType: 'runtime.before_step',
- },
- {
+ const beforeStepSignalEmission = await emitAgentSignalSourceEvent(
+ {
+ payload: {
agentId: beforeStepMetadata?.agentId,
- db: this.serverDB,
- userId: beforeStepMetadata?.userId || this.userId,
- workspaceId: this.workspaceId,
+ operationId,
+ serializedContext: undefined,
+ stepIndex,
+ topicId: beforeStepMetadata?.topicId,
+ turnCount: agentState?.stepCount || 0,
},
- { ignoreError: true },
- ),
+ sourceId: `${operationId}:before:${stepIndex}`,
+ sourceType: 'runtime.before_step',
+ },
+ {
+ agentId: beforeStepMetadata?.agentId,
+ db: this.serverDB,
+ userId: beforeStepMetadata?.userId || this.userId,
+ workspaceId: this.workspaceId,
+ },
+ { ignoreError: true },
);
beforeStepSignalEvents = toAgentSignalSnapshotEvents(beforeStepSignalEmission);
- await awaitStepWork(
- hookDispatcher.dispatch(
+ await hookDispatcher.dispatch(
+ operationId,
+ 'beforeStep',
+ {
+ agentId: beforeStepMetadata?.agentId || '',
+ finalState: agentState,
operationId,
- 'beforeStep',
- {
- agentId: beforeStepMetadata?.agentId || '',
- finalState: agentState,
- operationId,
- stepIndex,
- steps: agentState?.stepCount || 0,
- userId: beforeStepMetadata?.userId || this.userId,
- },
- beforeStepMetadata._hooks,
- ),
+ stepIndex,
+ steps: agentState?.stepCount || 0,
+ userId: beforeStepMetadata?.userId || this.userId,
+ },
+ beforeStepMetadata._hooks,
);
} catch (hookError) {
log('[%s] beforeStep hook dispatch error: %O', operationId, hookError);
@@ -1036,35 +1006,27 @@ export class AgentRuntimeService {
// Create Agent and Runtime instances
// Use agentState.metadata which contains the full app context (topicId, agentId, etc.)
// operationMetadata only contains basic fields (agentConfig, modelRuntimeConfig, userId)
- reportStage('runtime.create');
- const { runtime } = await awaitStepWork(
- this.createAgentRuntime({
- deadlineAt,
- metadata: agentState?.metadata,
- onStage,
- operationId,
- signal,
- stepIndex,
- tracingContextEngine: (input, output) => {
- contextEnginePayload = { input, output };
- },
- }),
- );
+ const { runtime } = await this.createAgentRuntime({
+ metadata: agentState?.metadata,
+ operationId,
+ stepIndex,
+ tracingContextEngine: (input, output) => {
+ contextEnginePayload = { input, output };
+ },
+ });
// Handle human intervention
let currentContext = context;
let currentState = agentState;
if (humanInput || approvedToolCall || rejectionReason) {
- const interventionResult = await awaitStepWork(
- this.humanIntervention.process(currentState, {
- approvedToolCall,
- humanInput,
- rejectAndContinue,
- rejectionReason,
- toolMessageId,
- }),
- );
+ const interventionResult = await this.humanIntervention.process(currentState, {
+ approvedToolCall,
+ humanInput,
+ rejectAndContinue,
+ rejectionReason,
+ toolMessageId,
+ });
currentState = interventionResult.newState;
currentContext = interventionResult.nextContext;
}
@@ -1074,7 +1036,7 @@ export class AgentRuntimeService {
// the pending set, refresh messages from the DB (to pick up the tool
// results written out-of-band), and re-enter the LLM with them.
if (resumeAsyncTool && currentState.status === 'waiting_for_async_tool') {
- const refreshed = await awaitStepWork(this.refreshMessagesFromDB(currentState));
+ const refreshed = await this.refreshMessagesFromDB(currentState);
const pendingTools = (currentState.pendingToolsCalling ?? []) as ChatToolPayload[];
const resumeParentMessageId = this.resolveAsyncToolResumeParentMessageId(
refreshed,
@@ -1106,7 +1068,7 @@ export class AgentRuntimeService {
// completion + dispatch hooks. Skips runtime.step entirely.
let forcedFinishState: AgentState | undefined;
if (finishAfterAsyncTool && currentState.status === 'waiting_for_async_tool') {
- const refreshed = await awaitStepWork(this.refreshMessagesFromDB(currentState));
+ const refreshed = await this.refreshMessagesFromDB(currentState);
currentState = structuredClone(currentState);
currentState.messages = refreshed;
currentState.pendingToolsCalling = [];
@@ -1125,7 +1087,7 @@ export class AgentRuntimeService {
// Pre-step computation: extract device context from DB messages
// Follows front-end computeStepContext pattern β€” computed at step boundary, not inside executors
if (!currentState.metadata?.activeDeviceId) {
- const deviceContext = await awaitStepWork(this.computeDeviceContext(currentState));
+ const deviceContext = await this.computeDeviceContext(currentState);
if (deviceContext && currentState.metadata) {
currentState.metadata.activeDeviceId = deviceContext.activeDeviceId;
currentState.metadata.devicePlatform = deviceContext.devicePlatform;
@@ -1140,12 +1102,10 @@ export class AgentRuntimeService {
}
// Execute step (skipped when force-finishing a parked supervisor op).
- reportStage('runtime.step');
- throwIfAgentStepAborted(signal);
const startAt = Date.now();
const stepResult = forcedFinishState
? { events: [], newState: forcedFinishState, nextContext: undefined }
- : await awaitStepWork(runtime.step(currentState, currentContext));
+ : await runtime.step(currentState, currentContext);
// Inner runtime.step() catches model-runtime exceptions and stuffs the
// raw error into newState.error without re-throwing β€” so the outer
@@ -1158,8 +1118,7 @@ export class AgentRuntimeService {
// Check if the operation was interrupted while the step was executing
// (e.g., user clicked abort during a long LLM call)
- reportStage('state.refresh');
- const latestState = await awaitStepWork(this.coordinator.loadAgentState(operationId));
+ const latestState = await this.coordinator.loadAgentState(operationId);
if (latestState?.status === 'interrupted') {
stepResult.newState.status = 'interrupted';
stepResult.newState.lastModified = new Date().toISOString();
@@ -1167,19 +1126,12 @@ export class AgentRuntimeService {
}
// Save state, coordinator will handle event sending automatically
- reportStage('state.save');
await this.coordinator.saveStepResult(operationId, {
...stepResult,
executionTime: Date.now() - startAt,
stepIndex, // placeholder
});
- // saveStepResult is the commit point for this step. Once it succeeds,
- // finish the bounded cleanup path even if the deadline fires: turning a
- // persisted `done` state into AgentStepTimeout would corrupt the terminal
- // result, while the route's outer runtime window reserves time for this
- // event/trace/hook/scheduling work.
-
// Decide whether to schedule next step
const shouldContinue = this.shouldContinueExecution(
stepResult.newState,
@@ -1188,7 +1140,6 @@ export class AgentRuntimeService {
let nextStepScheduled = false;
// Publish step complete event
- reportStage('gateway.publish_step_complete');
await this.streamManager.publishStreamEvent(operationId, {
data: {
finalState: stepResult.newState,
@@ -1226,7 +1177,6 @@ export class AgentRuntimeService {
// Dispatch afterStep hooks (enriched with step presentation + tracking data)
try {
- reportStage('hook.after_step');
const metadata = stepResult.newState?.metadata || {};
const tracking = metadata._stepTracking || {};
const elapsedMs = stepResult.newState?.createdAt
@@ -1296,7 +1246,6 @@ export class AgentRuntimeService {
log('[%s] afterStep hook dispatch error: %O', operationId, hookError);
}
- reportStage('trace.append');
await this.traceRecorder.appendStep(operationId, {
afterStepSignalEvents,
agentState,
@@ -1334,12 +1283,10 @@ export class AgentRuntimeService {
// Persist tracking state for next step
stepResult.newState.metadata._stepTracking = updatedTracking;
- reportStage('state.save_step_tracking');
await this.coordinator.saveAgentState(operationId, stepResult.newState);
}
if (shouldContinue && stepResult.nextContext && this.queueService) {
- reportStage('next_step.schedule');
const nextStepIndex = stepIndex + 1;
const delay = this.calculateStepDelay(stepResult);
const priority = this.calculatePriority(stepResult);
@@ -1383,7 +1330,6 @@ export class AgentRuntimeService {
buildInvokeAgentResultAttributes({ completionReason: reason }),
);
- reportStage('completion.hooks');
const completionSignalEvents = await this.completionLifecycle.emitSignalEvents(
operationId,
stepResult.newState,
@@ -1417,7 +1363,6 @@ export class AgentRuntimeService {
// recorder so propagated failures still write the canonical S3
// snapshot instead of orphaning the partial ().
const newStateError = stepResult.newState.error;
- reportStage('trace.finalize');
await this.traceRecorder.finalize(operationId, {
appendEventsToLastStep: completionSignalEvents,
completionReason: reason,
@@ -1466,7 +1411,6 @@ export class AgentRuntimeService {
// that completion callbacks and webhooks can still fire.
let finalStateWithError: any;
try {
- reportStage('error.publish');
await this.streamManager.publishStreamEvent(operationId, {
data: {
error: formattedError.message,
@@ -1486,7 +1430,6 @@ export class AgentRuntimeService {
}
try {
- reportStage('error.state_load');
const errorState = await this.coordinator.loadAgentState(operationId);
finalStateWithError = {
...errorState!,
@@ -1509,21 +1452,10 @@ export class AgentRuntimeService {
};
}
- let errorStateSaveError: unknown;
try {
- reportStage('error.state_save');
await this.coordinator.saveAgentState(operationId, finalStateWithError);
} catch (saveError) {
- errorStateSaveError = saveError;
log('[%s] Failed to save error state (infra may be down): %O', operationId, saveError);
- console.warn(
- JSON.stringify({
- event: 'agent.run_step.error_state_save_failed',
- operationId,
- stage: 'error.state_save',
- stepIndex,
- }),
- );
}
await this.completionLifecycle.emitSignalEvents(operationId, finalStateWithError, 'error');
@@ -1544,7 +1476,6 @@ export class AgentRuntimeService {
// success path could push it. Without this synthetic step, the
// snapshot's step count would lag the assistant message that
// triggered the failing call.
- reportStage('error.trace_finalize');
await this.traceRecorder.finalize(operationId, {
completionReason: 'error',
error: {
@@ -1567,21 +1498,6 @@ export class AgentRuntimeService {
state: finalStateWithError,
});
- if (isAgentStepTimeoutError(error)) {
- // `handled` is the ACK contract with the HTTP/QStash boundary: only a
- // durably persisted terminal timeout may return 2xx. A save failure
- // stays unhandled and is rethrown so QStash can retry the delivery.
- if (errorStateSaveError) {
- const saveError =
- errorStateSaveError instanceof Error
- ? errorStateSaveError
- : new Error(String(errorStateSaveError));
- saveError.cause ??= error;
- throw saveError;
- }
- markAgentStepTimeoutHandled(error);
- }
-
throw error;
} finally {
invokeAgentSpan.end();
@@ -2723,19 +2639,13 @@ export class AgentRuntimeService {
* Create Agent Runtime instance
*/
private async createAgentRuntime({
- deadlineAt,
metadata,
- onStage,
operationId,
- signal,
stepIndex,
tracingContextEngine,
}: {
- deadlineAt?: number;
metadata?: any;
- onStage?: (stage: string) => void;
operationId: string;
- signal?: AbortSignal;
stepIndex: number;
tracingContextEngine?: (input: unknown, output: unknown) => void;
}) {
@@ -2774,7 +2684,6 @@ export class AgentRuntimeService {
allowEarlyFinalAnswerVisibleOutputEnd: agent instanceof GeneralChatAgent,
botContext: metadata?.botContext,
botPlatformContext: metadata?.botPlatformContext,
- deadlineAt,
discordContext: metadata?.discordContext,
userTimezone: metadata?.userTimezone,
evalContext: metadata?.evalContext,
@@ -2784,10 +2693,8 @@ export class AgentRuntimeService {
hookDispatcher,
loadAgentState: this.coordinator.loadAgentState.bind(this.coordinator),
messageModel: this.messageModel,
- onStage,
operationId,
serverDB: this.serverDB,
- signal,
stepIndex,
stream: metadata?.stream,
streamManager: this.streamManager,
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index d6d38f8ac35..720f32717d3 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -4,7 +4,6 @@ import type { ReasoningGraph } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import { createRuntimeExecutors } from '@/server/modules/AgentRuntime/RuntimeExecutors';
-import { AgentStepTimeoutError } from '@/server/modules/AgentRuntime/stepDeadline';
import { AgentRuntimeService } from '../AgentRuntimeService';
import { hookDispatcher } from '../hooks';
@@ -197,34 +196,6 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
);
});
- it('threads the step deadline, signal, and stage reporter into runtime executors', async () => {
- vi.mocked(createRuntimeExecutors).mockClear();
- const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
- const controller = new AbortController();
- const onStage = vi.fn();
-
- await (service as any).createAgentRuntime({
- deadlineAt: 123_456,
- metadata: {
- agentConfig: {},
- modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- userId: 'user-1',
- },
- onStage,
- operationId: 'op-deadline',
- signal: controller.signal,
- stepIndex: 0,
- });
-
- expect(createRuntimeExecutors).toHaveBeenCalledWith(
- expect.objectContaining({
- deadlineAt: 123_456,
- onStage,
- signal: controller.signal,
- }),
- );
- });
-
it('disables early final visible output end for custom multi-step agents', async () => {
vi.mocked(createRuntimeExecutors).mockClear();
const service = new AgentRuntimeService({} as any, 'user-1', {
@@ -790,87 +761,6 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
});
describe('AgentRuntimeService.executeStep - error-path snapshot finalize ()', () => {
- it('persists AgentStepTimeout as a terminal error before marking it handled', async () => {
- const snapshotStore = {
- get: vi.fn(),
- getLatest: vi.fn(),
- list: vi.fn(),
- listPartials: vi.fn(),
- loadPartial: vi.fn().mockResolvedValue(null),
- removePartial: vi.fn().mockResolvedValue(undefined),
- save: vi.fn().mockResolvedValue(undefined),
- savePartial: vi.fn().mockResolvedValue(undefined),
- };
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: null,
- snapshotStore: snapshotStore as any,
- });
- const coordinator = (service as any).coordinator;
- const streamManager = (service as any).streamManager;
- const controller = new AbortController();
- const onStage = vi.fn();
- const timeoutError = new AgentStepTimeoutError({
- deadlineAt: Date.now(),
- stage: 'model.call',
- });
-
- coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);
- coordinator.releaseStepLock = vi.fn().mockResolvedValue(undefined);
- coordinator.loadAgentState = vi.fn().mockResolvedValue({
- lastModified: new Date().toISOString(),
- messages: [],
- metadata: {},
- status: 'running',
- stepCount: 0,
- });
- coordinator.saveAgentState = vi.fn().mockResolvedValue(undefined);
- streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);
- vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({
- runtime: {
- step: vi.fn().mockImplementation(async () => {
- controller.abort(timeoutError);
- return {
- events: [],
- newState: { status: 'running', stepCount: 0 },
- nextContext: undefined,
- };
- }),
- },
- });
- const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
-
- await expect(
- service.executeStep({
- context: { phase: 'user_input' } as any,
- deadlineAt: timeoutError.deadlineAt,
- onStage,
- operationId: 'op-timeout',
- signal: controller.signal,
- stepIndex: 0,
- }),
- ).rejects.toBe(timeoutError);
-
- expect(timeoutError.handled).toBe(true);
- expect(coordinator.saveAgentState).toHaveBeenCalledWith(
- 'op-timeout',
- expect.objectContaining({
- error: expect.objectContaining({ type: 'AgentStepTimeout' }),
- status: 'error',
- }),
- );
- expect(streamManager.publishStreamEvent).toHaveBeenCalledWith(
- 'op-timeout',
- expect.objectContaining({
- data: expect.objectContaining({ errorType: 'AgentStepTimeout' }),
- type: 'error',
- }),
- );
- expect(onStage).toHaveBeenCalledWith('error.state_save');
- expect(coordinator.releaseStepLock).toHaveBeenCalled();
-
- dispatchSpy.mockRestore();
- });
-
it('finalizes a snapshot with completionReason=error and a synthetic failed step when the executor throws', async () => {
const snapshotStore = {
get: vi.fn(),
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 969bd440049..5bf2e8a2c6f 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -131,8 +131,6 @@ export interface AgentExecutionParams {
*/
asyncToolVerifyAttempt?: number;
context?: AgentRuntimeContext;
- /** Absolute wall-clock deadline for this delivered step. */
- deadlineAt?: number;
externalRetryCount?: number;
/**
* Finish (rather than resume) a `waiting_for_async_tool` supervisor op after
@@ -151,8 +149,6 @@ export interface AgentExecutionParams {
*/
groupMemberTimeout?: GroupMemberTimeoutParams;
humanInput?: any;
- /** Reports the active execution stage for tracing and timeout diagnostics. */
- onStage?: (stage: string) => void;
operationId: string;
/**
* Whether a rejection should resume execution by treating the rejected tool
@@ -167,8 +163,6 @@ export interface AgentExecutionParams {
* via `tryResumeParentFromAsyncTool`.
*/
resumeAsyncTool?: boolean;
- /** Cooperative cancellation shared by the step's model and tool calls. */
- signal?: AbortSignal;
stepIndex: number;
/** ID of the pending tool message targeted by the intervention. */
toolMessageId?: string;
diff --git a/apps/server/src/services/sandbox/__tests__/serviceInit.test.ts b/apps/server/src/services/sandbox/__tests__/serviceInit.test.ts
index 71b79c87be0..38f471d1ef2 100644
--- a/apps/server/src/services/sandbox/__tests__/serviceInit.test.ts
+++ b/apps/server/src/services/sandbox/__tests__/serviceInit.test.ts
@@ -105,53 +105,6 @@ describe('SandboxMiddlewareService file initialization', () => {
expect(provider.callTool).toHaveBeenCalledWith('listFiles', {});
});
- it('enforces the server-resolved timeout at the provider boundary', async () => {
- const provider = createProvider();
- const service = new SandboxMiddlewareService(provider, {
- ...baseOptions(),
- executionTimeoutMs: 90_000,
- serverDB: undefined,
- });
-
- await service.callTool('runCommand', { command: 'sleep 900', timeout: 900_000 });
-
- expect(provider.callTool).toHaveBeenCalledWith('runCommand', {
- command: 'sleep 900',
- timeout: 90_000,
- });
- });
-
- it('preserves a caller timeout shorter than the server-resolved budget', async () => {
- const provider = createProvider();
- const service = new SandboxMiddlewareService(provider, {
- ...baseOptions(),
- executionTimeoutMs: 90_000,
- serverDB: undefined,
- });
-
- await service.callTool('runCommand', { command: 'sleep 5', timeout: 5000 });
-
- expect(provider.callTool).toHaveBeenCalledWith('runCommand', {
- command: 'sleep 5',
- timeout: 5000,
- });
- });
-
- it('does not add command timeout fields to non-command tools', async () => {
- const provider = createProvider();
- const service = new SandboxMiddlewareService(provider, {
- ...baseOptions(),
- executionTimeoutMs: 90_000,
- serverDB: undefined,
- });
-
- await service.callTool('readFile', { path: '/mnt/data/report.txt' });
-
- expect(provider.callTool).toHaveBeenCalledWith('readFile', {
- path: '/mnt/data/report.txt',
- });
- });
-
it('never blocks the tool call when the sync fails', async () => {
findFilesToInitInSandbox.mockRejectedValue(new Error('db down'));
const provider = createProvider();
diff --git a/apps/server/src/services/sandbox/providers/market.test.ts b/apps/server/src/services/sandbox/providers/market.test.ts
index 9c53e99a811..a8caebfa644 100644
--- a/apps/server/src/services/sandbox/providers/market.test.ts
+++ b/apps/server/src/services/sandbox/providers/market.test.ts
@@ -71,29 +71,6 @@ describe('MarketSandboxProvider', () => {
});
});
- it('forwards the agent step signal to the Market SDK request', async () => {
- const controller = new AbortController();
- const runBuildInTool = vi.fn(async () => ({ data: { result: {} }, success: true }));
- const marketService = {
- getSDK: vi.fn(() => ({ plugins: { runBuildInTool } })),
- } as unknown as MarketService;
- const provider = new MarketSandboxProvider({
- marketService,
- signal: controller.signal,
- topicId: 'topic-1',
- userId: 'user-1',
- });
-
- await provider.callTool('runCommand', { command: 'sleep 900', timeout: 120_000 });
-
- expect(runBuildInTool).toHaveBeenCalledWith(
- 'runCommand',
- { command: 'sleep 900', timeout: 120_000 },
- { topicId: 'topic-1', userId: 'user-1' },
- { signal: controller.signal },
- );
- });
-
it('preserves Market sandbox export error codes for authorization handling', async () => {
const marketService = createMarketService({
error: {
diff --git a/apps/server/src/services/sandbox/providers/market.ts b/apps/server/src/services/sandbox/providers/market.ts
index c8dd1b9c232..78a43953994 100644
--- a/apps/server/src/services/sandbox/providers/market.ts
+++ b/apps/server/src/services/sandbox/providers/market.ts
@@ -49,15 +49,12 @@ export class MarketSandboxProvider implements SandboxProvider {
);
try {
- const response = await marketService.getSDK().plugins.runBuildInTool(
- toolName as CodeInterpreterToolName,
- params as never,
- {
+ const response = await marketService
+ .getSDK()
+ .plugins.runBuildInTool(toolName as CodeInterpreterToolName, params as never, {
topicId,
userId,
- },
- this.options.signal ? { signal: this.options.signal } : undefined,
- );
+ });
log('Sandbox tool %s response: %O', toolName, response);
diff --git a/apps/server/src/services/sandbox/providers/onlyboxes.test.ts b/apps/server/src/services/sandbox/providers/onlyboxes.test.ts
index 41e0504925a..3983f1df1ae 100644
--- a/apps/server/src/services/sandbox/providers/onlyboxes.test.ts
+++ b/apps/server/src/services/sandbox/providers/onlyboxes.test.ts
@@ -48,7 +48,6 @@ describe('OnlyboxesSandboxProvider', () => {
});
it('maps runCommand to the terminal command endpoint with a persistent session', async () => {
- const controller = new AbortController();
const fetchMock = vi.fn(async () => {
return new Response(
JSON.stringify({
@@ -65,7 +64,6 @@ describe('OnlyboxesSandboxProvider', () => {
const { OnlyboxesSandboxProvider } = await import('./onlyboxes');
const provider = new OnlyboxesSandboxProvider({
marketService: {} as MarketService,
- signal: controller.signal,
topicId: 'topic-1',
userId: 'user-1',
});
@@ -87,7 +85,6 @@ describe('OnlyboxesSandboxProvider', () => {
timeout_ms: 120_000,
}),
method: 'POST',
- signal: controller.signal,
}),
);
const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
diff --git a/apps/server/src/services/sandbox/providers/onlyboxes.ts b/apps/server/src/services/sandbox/providers/onlyboxes.ts
index 70807d926aa..3f9737f0016 100644
--- a/apps/server/src/services/sandbox/providers/onlyboxes.ts
+++ b/apps/server/src/services/sandbox/providers/onlyboxes.ts
@@ -660,7 +660,6 @@ export class OnlyboxesSandboxProvider implements SandboxProvider {
const response = await fetch(`${this.baseUrl}${path}`, {
...init,
headers,
- ...(this.options.signal && { signal: this.options.signal }),
});
const body = await response.text();
const json = body ? JSON.parse(body) : {};
diff --git a/apps/server/src/services/sandbox/service.ts b/apps/server/src/services/sandbox/service.ts
index 83df42dee55..780ad26072f 100644
--- a/apps/server/src/services/sandbox/service.ts
+++ b/apps/server/src/services/sandbox/service.ts
@@ -24,8 +24,6 @@ import type {
const log = debug('lobe-server:sandbox:service');
-const TIMEOUT_AWARE_TOOL_NAMES = new Set(['execScript', 'runCommand']);
-
export class SandboxMiddlewareService implements SandboxService {
readonly capabilities: SandboxProviderCapabilities;
readonly kind: SandboxProviderKind;
@@ -45,23 +43,7 @@ export class SandboxMiddlewareService implements SandboxService {
params: Record<string, unknown>,
): Promise<SandboxCallToolResult> {
await this.ensureFilesInitialized();
- const requestedTimeout =
- typeof params.timeout === 'number' && Number.isFinite(params.timeout) && params.timeout > 0
- ? params.timeout
- : undefined;
- const executionTimeoutMs = this.options.executionTimeoutMs;
- const resolvedParams =
- executionTimeoutMs === undefined || !TIMEOUT_AWARE_TOOL_NAMES.has(toolName)
- ? params
- : {
- ...params,
- timeout:
- requestedTimeout === undefined
- ? executionTimeoutMs
- : Math.min(requestedTimeout, executionTimeoutMs),
- };
-
- return this.provider.callTool(toolName, resolvedParams);
+ return this.provider.callTool(toolName, params);
}
/**
diff --git a/apps/server/src/services/sandbox/types.ts b/apps/server/src/services/sandbox/types.ts
index 4fedf6d1628..0c6e95c0a7b 100644
--- a/apps/server/src/services/sandbox/types.ts
+++ b/apps/server/src/services/sandbox/types.ts
@@ -15,14 +15,10 @@ export interface SandboxSessionContext {
}
export interface SandboxServiceOptions extends SandboxSessionContext {
- /** Server-resolved timeout for the current tool execution. */
- executionTimeoutMs?: number;
fileService?: FileService;
marketService: MarketService;
/** Used to look up topic/session files when bootstrapping the sandbox. */
serverDB?: LobeChatDatabase;
- /** Cooperative cancellation inherited from the containing agent step. */
- signal?: AbortSignal;
}
export interface SandboxProviderCapabilities {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
index 5239bd61f10..9756528a187 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
@@ -210,28 +210,6 @@ describe('skillsRuntime', () => {
expect(result.state).toMatchObject({ executionEnv: 'sandbox' });
});
- it('passes the resolved timeout and step signal into the cloud sandbox service', async () => {
- const controller = new AbortController();
- const { skillsRuntime } = await import('../skills');
- const runtime = await skillsRuntime.factory({
- executionTimeoutMs: 120_000,
- serverDB: {} as never,
- signal: controller.signal,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
- });
-
- await runtime.runCommand({ command: 'sleep 900' });
-
- expect(mocks.createSandboxService).toHaveBeenCalledWith(
- expect.objectContaining({
- executionTimeoutMs: 120_000,
- signal: controller.signal,
- }),
- );
- });
-
it('passes workspace scope when preprocessing sandbox lh commands', async () => {
mocks.preprocessLhCommand.mockResolvedValueOnce({
command: 'LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent edit agt_123',
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
index 3123a999672..c2eef901f4f 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
@@ -26,11 +26,9 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {
const marketService = new MarketService({ userInfo: { userId: context.userId } });
const fileService = new FileService(context.serverDB, context.userId, context.workspaceId);
const sandboxService = createSandboxService({
- executionTimeoutMs: context.executionTimeoutMs,
fileService,
marketService,
serverDB: context.serverDB,
- signal: context.signal,
topicId: context.topicId,
userId: context.userId,
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index 0ba976caeb9..201aec71f6e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -101,7 +101,6 @@ const isLhCommand = (command: string) => LH_COMMAND_PATTERN.test(command);
class SkillServerRuntimeService implements SkillRuntimeService {
private agentId?: string;
- private executionTimeoutMs?: number;
private resourceService: SkillResourceService;
private skillModel: AgentSkillModel;
private marketService: MarketService;
@@ -113,7 +112,6 @@ class SkillServerRuntimeService implements SkillRuntimeService {
private workspaceId?: string;
private device?: SkillDeviceExecution;
private disabledSkillIds: Set<string>;
- private signal?: AbortSignal;
constructor(options: {
agentId?: string;
@@ -125,7 +123,6 @@ class SkillServerRuntimeService implements SkillRuntimeService {
* its name, independent of whatever's listed in `<available_skills>`.
*/
disabledSkillIds?: Set<string>;
- executionTimeoutMs?: number;
fileModel: FileModel;
fileService: FileService;
marketService: MarketService;
@@ -135,10 +132,8 @@ class SkillServerRuntimeService implements SkillRuntimeService {
topicId?: string;
userId: string;
workspaceId?: string;
- signal?: AbortSignal;
}) {
this.agentId = options.agentId;
- this.executionTimeoutMs = options.executionTimeoutMs;
this.skillModel = options.skillModel;
this.resourceService = options.resourceService;
this.marketService = options.marketService;
@@ -150,20 +145,8 @@ class SkillServerRuntimeService implements SkillRuntimeService {
this.workspaceId = options.workspaceId;
this.device = options.device;
this.disabledSkillIds = options.disabledSkillIds ?? new Set();
- this.signal = options.signal;
}
- private createSandbox = (topicId: string) =>
- createSandboxService({
- executionTimeoutMs: this.executionTimeoutMs,
- fileService: this.fileService,
- marketService: this.marketService,
- serverDB: this.serverDB,
- signal: this.signal,
- topicId,
- userId: this.userId,
- });
-
findAll = (): Promise<{ data: SkillListItem[]; total: number }> => {
return this.skillModel.findAll();
};
@@ -229,7 +212,13 @@ class SkillServerRuntimeService implements SkillRuntimeService {
}
try {
- const sandboxService = this.createSandbox(this.topicId);
+ const sandboxService = createSandboxService({
+ fileService: this.fileService,
+ marketService: this.marketService,
+ serverDB: this.serverDB,
+ topicId: this.topicId,
+ userId: this.userId,
+ });
const response = await sandboxService.callTool('runCommand', { command: lhResult.command });
log('runCommand response: %O', response);
@@ -532,7 +521,13 @@ class SkillServerRuntimeService implements SkillRuntimeService {
);
}
- const sandboxService = this.createSandbox(this.topicId);
+ const sandboxService = createSandboxService({
+ fileService: this.fileService,
+ marketService: this.marketService,
+ serverDB: this.serverDB,
+ topicId: this.topicId,
+ userId: this.userId,
+ });
const response = await sandboxService.callTool('execScript', enhancedParams);
log('execScript response: %O', response);
@@ -574,7 +569,12 @@ class SkillServerRuntimeService implements SkillRuntimeService {
}
try {
- const sandboxService = this.createSandbox(this.topicId);
+ const sandboxService = createSandboxService({
+ fileService: this.fileService,
+ marketService: this.marketService,
+ topicId: this.topicId,
+ userId: this.userId,
+ });
const result = await sandboxService.exportAndUploadFile(path, filename);
return {
@@ -674,7 +674,6 @@ export const skillsRuntime: ServerRuntimeRegistration = {
agentId: context.agentId,
device,
disabledSkillIds,
- executionTimeoutMs: context.executionTimeoutMs,
fileModel,
fileService,
marketService,
@@ -684,7 +683,6 @@ export const skillsRuntime: ServerRuntimeRegistration = {
topicId: context.topicId,
userId: context.userId,
workspaceId: context.workspaceId,
- signal: context.signal,
});
// Surface this agent's skill-bundle documents as `BuiltinSkill`-shaped
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index c5cfd20c35d..022c40c9ed3 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -171,8 +171,6 @@ export interface ToolExecutionContext {
* `messageId`.
*/
assistantMessageId?: string;
- /** Absolute wall-clock deadline inherited from the containing agent step. */
- deadlineAt?: number;
/**
* Whether the run's execution plan is device-capable (`device` or
* `device-unrouted`) β€” derived from `state.metadata.executionPlan` by the
@@ -237,8 +235,6 @@ export interface ToolExecutionContext {
scope?: string | null;
/** Server database for LobeHub Skills execution */
serverDB?: LobeChatDatabase;
- /** Cooperative cancellation inherited from the containing agent step. */
- signal?: AbortSignal;
/** Skip low-level result truncation so the AgentRuntime boundary can archive full content first. */
skipResultTruncation?: boolean;
/**
diff --git a/packages/observability-otel/src/modules/agent-runtime/semconv.ts b/packages/observability-otel/src/modules/agent-runtime/semconv.ts
index 1068a0bceb1..5e4572e56cb 100644
--- a/packages/observability-otel/src/modules/agent-runtime/semconv.ts
+++ b/packages/observability-otel/src/modules/agent-runtime/semconv.ts
@@ -83,15 +83,9 @@ export const ATTR_LOBEHUB_TOOL_SUCCESS = 'lobehub.tool.success' as const;
/** Attempts taken to execute a tool (1 for first-try success). */
export const ATTR_LOBEHUB_TOOL_ATTEMPTS = 'lobehub.tool.attempts' as const;
-/** Runtime target that executed the tool (`client` / `device` / `server`). */
-export const ATTR_LOBEHUB_TOOL_EXECUTION_TARGET = 'lobehub.tool.execution_target' as const;
-
/** Internal LobeHub tool source (`builtin` / `client` / `mcp` / `composio` / `lobehubSkill`). */
export const ATTR_LOBEHUB_TOOL_SOURCE = 'lobehub.tool.source' as const;
-/** Effective timeout assigned to the tool after clamping to the remaining step budget. */
-export const ATTR_LOBEHUB_TOOL_TIMEOUT_MS = 'lobehub.tool.timeout_ms' as const;
-
/** Context engineering metadata. */
export const ATTR_LOBEHUB_CONTEXT_MESSAGE_COUNT = 'lobehub.context.message_count' as const;
export const ATTR_LOBEHUB_CONTEXT_TOKEN_USAGE = 'lobehub.context.token_usage' as const;