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.

⚡️ perf(agent): run step 0 inline after execAgent responds (behind agent_inline_first_step) (#22946)

Arvin Xuac0c3613eeea
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index 5bafad7de40..9b43005878b 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -400,6 +400,19 @@ export class AgentRuntimeCoordinator {
return this.stateManager.clearInlineResume(operationId, ownerId);
}
+ /**
+ * Record that the `execAgent` invocation running step 0 inline is done with
+ * it, so the queued fallback delivery of step 0 is acknowledged unrun.
+ */
+ async markInlineFirstStepSettled(operationId: string): Promise<void> {
+ return this.stateManager.markInlineFirstStepSettled(operationId);
+ }
+
+ /** Whether {@link markInlineFirstStepSettled} ran for this operation. */
+ async isInlineFirstStepSettled(operationId: string): Promise<boolean> {
+ return this.stateManager.isInlineFirstStepSettled(operationId);
+ }
+
/**
* Atomically try to claim a step for execution (distributed lock).
*/
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index 3508be9b73d..13964407ec4 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -241,6 +241,7 @@ export class AgentStateManager {
private readonly INTERRUPT_PREFIX = 'agent_runtime_interrupt';
private readonly QUEUED_MESSAGES_PREFIX = 'agent_runtime_queued_messages';
private readonly INLINE_RESUME_PREFIX = 'agent_runtime_inline_resume';
+ private readonly INLINE_FIRST_STEP_PREFIX = 'agent_runtime_inline_first_step';
private readonly DEFAULT_TTL = 2 * 3600; // 2h
constructor() {
@@ -659,6 +660,7 @@ export class AgentStateManager {
`${this.INTERRUPT_PREFIX}:${operationId}`,
`${this.QUEUED_MESSAGES_PREFIX}:${operationId}`,
`${this.INLINE_RESUME_PREFIX}:${operationId}`,
+ `${this.INLINE_FIRST_STEP_PREFIX}:${operationId}`,
];
try {
@@ -824,6 +826,33 @@ export class AgentStateManager {
}
}
+ /**
+ * Best-effort: without the marker the fallback delivery of step 0 runs as a
+ * redelivery, and the step claim plus the stale-step guards still keep it
+ * from running the step twice.
+ */
+ async markInlineFirstStepSettled(operationId: string): Promise<void> {
+ try {
+ await this.redis.setex(
+ `${this.INLINE_FIRST_STEP_PREFIX}:${operationId}`,
+ this.DEFAULT_TTL,
+ '1',
+ );
+ } catch (error) {
+ console.error('Failed to mark inline first step settled:', error);
+ }
+ }
+
+ /** A read failure answers false: the delivery then runs as a redelivery. */
+ async isInlineFirstStepSettled(operationId: string): Promise<boolean> {
+ try {
+ return (await this.redis.get(`${this.INLINE_FIRST_STEP_PREFIX}:${operationId}`)) === '1';
+ } catch (error) {
+ console.error('Failed to read inline first step marker:', error);
+ return false;
+ }
+ }
+
private executionLockKey(operationId: string): string {
return `agent_runtime_operation_lock:${operationId}`;
}
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
index 8468743a28a..0be00f828d5 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
@@ -16,6 +16,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
private metadata: Map<string, AgentOperationMetadata> = new Map();
private stepLocks: Map<string, { expiresAt: number; ownerId: string }> = new Map();
private inlineResumes: Map<string, string> = new Map();
+ private inlineFirstStepsSettled: Set<string> = new Set();
private interrupted: Set<string> = new Set();
private queuedMessages: Set<string> = new Set();
@@ -162,6 +163,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
this.interrupted.delete(operationId);
this.queuedMessages.delete(operationId);
this.inlineResumes.delete(operationId);
+ this.inlineFirstStepsSettled.delete(operationId);
log('Deleted operation %s', operationId);
}
@@ -252,6 +254,14 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
this.inlineResumes.delete(operationId);
}
+ async markInlineFirstStepSettled(operationId: string): Promise<void> {
+ this.inlineFirstStepsSettled.add(operationId);
+ }
+
+ async isInlineFirstStepSettled(operationId: string): Promise<boolean> {
+ return this.inlineFirstStepsSettled.has(operationId);
+ }
+
async tryClaimStep(
operationId: string,
_stepIndex: number,
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
index 19396a5190e..6ada31fc352 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
@@ -719,10 +719,40 @@ describe('AgentStateManager', () => {
'agent_runtime_interrupt:op-del',
'agent_runtime_queued_messages:op-del',
'agent_runtime_inline_resume:op-del',
+ 'agent_runtime_inline_first_step:op-del',
);
});
});
+ describe('inline first step marker', () => {
+ it('marks the step settled with the state TTL and reads it back', async () => {
+ await stateManager.markInlineFirstStepSettled('op-inline');
+
+ expect(redisMock.setex).toHaveBeenCalledWith(
+ 'agent_runtime_inline_first_step:op-inline',
+ 2 * 3600,
+ '1',
+ );
+
+ redisMock.get.mockResolvedValueOnce('1');
+ await expect(stateManager.isInlineFirstStepSettled('op-inline')).resolves.toBe(true);
+ redisMock.get.mockResolvedValueOnce(null);
+ await expect(stateManager.isInlineFirstStepSettled('op-inline')).resolves.toBe(false);
+ });
+
+ // Unread or unwritten, the fallback delivery still runs as a redelivery and
+ // the step claim keeps it from running the step twice.
+ it('treats an unreachable Redis as not settled, and a failed mark as best-effort', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ redisMock.get.mockRejectedValueOnce(new Error('ECONNRESET'));
+ redisMock.setex.mockRejectedValueOnce(new Error('ECONNRESET'));
+
+ await expect(stateManager.isInlineFirstStepSettled('op-inline')).resolves.toBe(false);
+ await expect(stateManager.markInlineFirstStepSettled('op-inline')).resolves.toBeUndefined();
+ errorSpy.mockRestore();
+ });
+ });
+
describe('queued messages flag', () => {
it('setQueuedMessages(true) writes a small key with the state TTL', async () => {
await stateManager.setQueuedMessages('op-q', true);
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index 508c24cbc33..f7aadae1b80 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -109,6 +109,12 @@ export interface IAgentStateManager {
*/
hasQueuedMessages: (operationId: string) => Promise<boolean>;
+ /**
+ * Whether the `execAgent` invocation that ran step 0 inline finished with it
+ * (see `markInlineFirstStepSettled`). False when it cannot be read.
+ */
+ isInlineFirstStepSettled: (operationId: string) => Promise<boolean>;
+
/**
* Check the interrupt sentinel written by `markInterrupted`. Cheap enough
* to poll, unlike `loadAgentState` which pulls the whole state blob.
@@ -123,6 +129,13 @@ export interface IAgentStateManager {
/** Read the inline step loop's parked envelope, if any. */
loadInlineResume: (operationId: string) => Promise<null | string>;
+ /**
+ * Record that the `execAgent` invocation running step 0 inline finished its
+ * step loop without throwing, so the queued fallback delivery of step 0 has
+ * nothing left to do. Best-effort.
+ */
+ markInlineFirstStepSettled: (operationId: string) => Promise<void>;
+
/**
* Set the interrupt sentinel for the operation, alongside the
* authoritative `status: 'interrupted'` in the persisted state.
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
index 2e807244be6..fd577d0f448 100644
--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
@@ -30,6 +30,7 @@ const initialDoneResult = () => ({
const mockGetOperationMetadata = vi.fn();
const mockLoadInlineResume = vi.fn();
const mockClearInlineResume = vi.fn();
+const mockIsInlineFirstStepSettled = vi.fn();
const mockExecuteStep = vi.fn();
const mockScheduleContinuation = vi.fn();
const mockReleaseOperationLock = vi.fn();
@@ -59,6 +60,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
return {
clearInlineResume: mockClearInlineResume,
getOperationMetadata: mockGetOperationMetadata,
+ isInlineFirstStepSettled: mockIsInlineFirstStepSettled,
loadInlineResume: mockLoadInlineResume,
};
}),
@@ -909,3 +911,67 @@ describe('runStep inline step loop', () => {
expect(getCaptures()[0].body).toMatchObject({ inlinedSteps: 1 });
});
});
+
+describe('runStep fallback of an inline step 0 (agent_inline_first_step)', () => {
+ const fallbackBody = {
+ context: { phase: 'user_input' },
+ operationId: 'op-1',
+ payload: { inlineFirstStepFallback: true },
+ stepIndex: 0,
+ };
+
+ beforeEach(() => {
+ mockGetOperationMetadata.mockReset();
+ mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1', workspaceId: 'ws-1' });
+ mockExecuteStep.mockReset();
+ mockIsInlineFirstStepSettled.mockReset();
+ mockLoadInlineResume.mockReset();
+ mockLoadInlineResume.mockResolvedValue(null);
+ mockReleaseOperationLock.mockReset();
+ mockGetServerDB.mockResolvedValue({} as any);
+ });
+
+ it('acknowledges without running anything once the inline run settled step 0', async () => {
+ mockIsInlineFirstStepSettled.mockResolvedValue(true);
+
+ const { ctx, getCaptures } = buildContext({ body: fallbackBody });
+ const res = await runStep(ctx);
+
+ expect(res.status).toBe(200);
+ expect(getCaptures()[0].body).toMatchObject({ inlineFirstStepSettled: true, success: true });
+ expect(mockExecuteStep).not.toHaveBeenCalled();
+ expect(mockLoadInlineResume).not.toHaveBeenCalled();
+ });
+
+ it("runs as step 0's redelivery while the inline run has not settled it", async () => {
+ mockIsInlineFirstStepSettled.mockResolvedValue(false);
+ mockExecuteStep.mockResolvedValueOnce(initialDoneResult());
+
+ const { ctx } = buildContext({ body: fallbackBody });
+ const res = await runStep(ctx);
+
+ expect(res.status).toBe(200);
+ expect(mockExecuteStep).toHaveBeenCalledTimes(1);
+ expect(mockExecuteStep).toHaveBeenCalledWith(
+ expect.objectContaining({
+ // Replays a parked approval whose Review the inline run failed to persist.
+ externalRetryCount: 1,
+ firstStepDispatch: 'inline_fallback',
+ operationId: 'op-1',
+ stepIndex: 0,
+ }),
+ );
+ });
+
+ it('leaves an ordinary delivery of step 0 alone', async () => {
+ mockExecuteStep.mockResolvedValueOnce(initialDoneResult());
+
+ const { ctx } = buildContext({ body: { ...fallbackBody, payload: undefined } });
+ await runStep(ctx);
+
+ expect(mockIsInlineFirstStepSettled).not.toHaveBeenCalled();
+ expect(mockExecuteStep).toHaveBeenCalledWith(
+ expect.objectContaining({ externalRetryCount: 0, firstStepDispatch: undefined }),
+ );
+ });
+});
diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.ts
index 221eb9206f5..63a382ee7e2 100644
--- a/apps/server/src/router-hono/agent/handlers/runStep.ts
+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts
@@ -9,17 +9,11 @@ import { agentOperations } from '@/database/schemas/agentOperations';
import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';
import {
AbandonOperationService,
- type AgentExecutionResult,
- type AgentStepContinuation,
scheduleOpportunisticStaleSweep,
scheduleOpportunisticVerifySweep,
} from '@/server/services/agentRuntime';
import { AiAgentService } from '@/server/services/aiAgent';
-import { runWithInvocationDeadline } from '@/server/utils/invocationDeadline';
-import {
- flushScheduledWork,
- runWithScheduledWorkScope,
-} from '@/server/utils/scheduleAfterResponse';
+import { runStepInvocation } from '@/server/services/aiAgent/stepInvocation';
import { resumeAbandonedParent } from './resumeAbandonedParent';
@@ -51,17 +45,6 @@ const log = debug('lobe-server:agent:run-step');
*/
const INLINE_STEP_START_DEADLINE_MS = Number(process.env.AGENT_INLINE_STEP_DEADLINE_MS ?? 450_000);
-/**
- * Longest the loop waits at a step boundary for work the previous step
- * deferred with `after()`.
- *
- * That work includes settling the step's budget hold, which has to finish
- * before the next step reserves again. It normally takes well under a second.
- * The cap only stops one stuck telemetry call from stalling the operation;
- * anything still running keeps going.
- */
-const STEP_BOUNDARY_FLUSH_TIMEOUT_MS = 10_000;
-
/**
* The route's `maxDuration`: when the host kills this invocation, counted from
* the start of the request.
@@ -219,6 +202,7 @@ export async function runStep(c: Context): Promise<Response> {
asyncToolVerifyAttempt,
resumeClientLlm,
clientLlmWaitExpired,
+ inlineFirstStepFallback,
lockRetryAttempt,
} = { ...body, ...body.payload };
@@ -226,6 +210,25 @@ export async function runStep(c: Context): Promise<Response> {
return c.json({ error: 'operationId is required' }, 400);
}
+ // The queued fallback of a step 0 that `execAgent` ran inline
+ // (`agent_inline_first_step`). Once that invocation settled its step loop,
+ // whatever it left behind (a finished run, a parked one, a continuation it
+ // queued) is owned elsewhere, so this delivery has nothing to do. Without
+ // the marker the inline run is still going, never started, or died: run as
+ // the queue's redelivery of step 0 and let the step claim decide.
+ const coordinator = new AgentRuntimeCoordinator();
+ const firstStepFallback = inlineFirstStepFallback === true;
+ if (firstStepFallback && (await coordinator.isInlineFirstStepSettled(operationId))) {
+ log(`[${operationId}] Inline step ${stepIndex} already settled; fallback is a no-op`);
+ return c.json({
+ inlineFirstStepSettled: true,
+ nextStepScheduled: false,
+ operationId,
+ stepIndex,
+ success: true,
+ });
+ }
+
log(`[${operationId}] Starting step ${stepIndex}`);
// Ride the always-exercised step path to run the stale-operation sweep, at
@@ -240,7 +243,6 @@ export async function runStep(c: Context): Promise<Response> {
scheduleOpportunisticVerifySweep();
// Get userId from operation metadata stored in Redis
- const coordinator = new AgentRuntimeCoordinator();
const metadata = await coordinator.getOperationMetadata(operationId);
if (!metadata?.userId) {
@@ -284,186 +286,39 @@ export async function runStep(c: Context): Promise<Response> {
// ===== Inline step loop =====
// Keep stepping inside this invocation for as long as the operation has a
- // next step ready and the deadline allows, instead of paying a queue
- // round-trip per step. One lock owner spans the whole loop: the operation
- // lock is re-entrant for its owner, so a redelivery from the queue still
- // loses the race the same way it does for a single step.
-
- const stepLockOwner = aiAgentService.createOperationLockOwner(operationId);
- let pendingContinuation: AgentStepContinuation | undefined;
- let currentStepIndex = stepIndex;
- let inlinedSteps = 0;
- let result!: AgentExecutionResult;
- // True once this invocation has an envelope to account for: either it
- // resumed from one, or a step handed back a continuation (which parks one).
- let touchedEnvelope = false;
-
- // Only a plain "run the next step" delivery may be redirected to a parked
- // envelope. Anything carrying its own purpose — an approval, a resume, a
- // watchdog probe — has to run as itself: redirecting it would drop that
- // payload and silently turn it into an ordinary step. The group-member
- // timeout is the sharp edge, because it is always scheduled at stepIndex 0
- // on the member operation, so any envelope at all would swallow it and take
- // the running loop's recovery pointer down with it.
- const isPlainStepDelivery =
- humanInput === undefined &&
- approvedToolCall === undefined &&
- rejectionReason === undefined &&
- toolMessageId === undefined &&
- !rejectAndContinue &&
- !resumeAsyncTool &&
- !finishAfterAsyncTool &&
- !verifyAsyncToolBarrier &&
- !resumeClientLlm &&
- !clientLlmWaitExpired &&
- !groupMemberTimeout;
-
- // A previous invocation may have died part-way through its own inline loop.
- // It parks the envelope for each step before running it, so an envelope
- // ahead of the delivered index means exactly that: resume from there. Going
- // ahead with the delivered index instead would hit the `stepCount >
- // stepIndex` stale-delivery guard, get ACKed, and strand the operation with
- // nothing queued behind it.
- const parked = isPlainStepDelivery
- ? await coordinator.loadInlineResume<AgentStepContinuation>(operationId)
- : null;
- const resumeFrom = parked && parked.stepIndex > stepIndex ? parked : undefined;
- if (resumeFrom) {
- log(
- `[${operationId}] Delivered step ${stepIndex} is behind a parked inline step ${resumeFrom.stepIndex}; resuming there`,
- );
- currentStepIndex = resumeFrom.stepIndex;
- touchedEnvelope = true;
- }
-
- try {
- // Work a step defers with `after()` (budget settlement, trace flushes,
- // telemetry) normally waits for the HTTP response. One invocation now
- // spans many steps, so every earlier step's budget hold would stay
- // reserved until the loop ends and squeeze the next reservation. Scoping
- // it to the loop starts that work immediately and lets each boundary wait
- // for it, which is how it behaved when every step was its own request.
- // Long waits inside a step (a relayed LLM attempt) size themselves to
- // what is left of this invocation.
- await runWithInvocationDeadline(startTime + STEP_INVOCATION_MAX_DURATION_MS, () =>
- runWithScheduledWorkScope(async () => {
- // The first iteration carries this delivery's one-shot payload (human
- // input, approvals, resume flags). Later iterations are plain steps, so
- // they must not replay any of it, and neither must a resumed run — it
- // stands in for a later iteration of a dead loop, not for the original
- // message.
- //
- // `externalRetryCount` is the exception, because it describes this
- // delivery rather than the step's payload. A parked approval whose Review
- // failed to persist is only replayed when the count is nonzero, so
- // dropping it here would leave that approval permanently unavailable.
- result = resumeFrom
- ? await aiAgentService.executeStep({
- context: resumeFrom.context,
- externalRetryCount,
- inlineContinuation: true,
- operationId,
- retainStepLock: true,
- stepIndex: resumeFrom.stepIndex,
- stepLockOwner,
- })
- : await aiAgentService.executeStep({
- approvedToolCall,
- asyncToolVerifyAttempt,
- clientLlmWaitExpired,
- context,
- externalRetryCount,
- finishAfterAsyncTool,
- groupMemberTimeout,
- humanInput,
- inlineContinuation: true,
- lockRetryAttempt,
- operationId,
- rejectAndContinue,
- rejectionReason,
- resumeAsyncTool,
- resumeClientLlm,
- retainStepLock: true,
- stepIndex,
- stepLockOwner,
- toolMessageId,
- verifyAsyncToolBarrier,
- });
- pendingContinuation = result.continuation;
- touchedEnvelope ||= Boolean(pendingContinuation);
-
- while (pendingContinuation) {
- // Let the previous step's deferred work finish first. Its budget
- // hold is released there, and the next step reserves again.
- const settled = await flushScheduledWork({ timeoutMs: STEP_BOUNDARY_FLUSH_TIMEOUT_MS });
- if (!settled) {
- // The deferred work cannot be told apart, so a slow telemetry call
- // and a slow budget settlement look the same. Reserving again on
- // top of an unreleased hold is exactly the false "over budget"
- // this wait exists to prevent, so stop inlining and hand the step
- // to the queue, the way it ran before steps were inlined.
- log(
- `[${operationId}] Deferred work still running after ${STEP_BOUNDARY_FLUSH_TIMEOUT_MS}ms, handing step ${pendingContinuation.stepIndex} back to the queue`,
- );
- break;
- }
-
- const elapsed = Date.now() - startTime;
- if (elapsed >= INLINE_STEP_START_DEADLINE_MS) {
- log(
- `[${operationId}] Inline budget spent after ${inlinedSteps} extra step(s) (${elapsed}ms), handing step ${pendingContinuation.stepIndex} back to the queue`,
- );
- break;
- }
-
- const next = pendingContinuation;
- pendingContinuation = undefined;
- currentStepIndex = next.stepIndex;
-
- result = await aiAgentService.executeStep({
- context: next.context,
- inlineContinuation: true,
- operationId,
- retainStepLock: true,
- stepIndex: next.stepIndex,
- stepLockOwner,
- });
- inlinedSteps += 1;
- pendingContinuation = result.continuation;
- touchedEnvelope ||= Boolean(pendingContinuation);
-
- // A lock conflict mid-loop means another worker took over this
- // operation. Stop rather than fight it — that worker owns the rest.
- if (result.locked) break;
- }
-
- // Whatever is still pending goes back to the queue so the operation
- // resumes in a fresh invocation.
- if (pendingContinuation) {
- await aiAgentService.scheduleContinuation(pendingContinuation);
- result = { ...result, nextStepScheduled: true };
- pendingContinuation = undefined;
- }
-
- // Drop the envelope once this invocation is done with it: either the queue
- // owns the next step again, or the operation stopped. Leaving it behind
- // would let a late redelivery re-run a step someone else already owns.
- // Skipped when nothing was ever parked, to keep the flag-off path free of
- // an extra Redis round-trip.
- //
- // Scoped to our lock owner, because "done with it" is only true while we
- // still hold the operation. A delivery that read an envelope and then lost
- // the lock race must not delete the newer one the live worker parked.
- if (touchedEnvelope) {
- await coordinator.clearInlineResume(operationId, stepLockOwner);
- }
- }),
- );
- } finally {
- // Owner-scoped, so this is a no-op when the first step never claimed the
- // lock (a conflicting delivery, a terminal operation, a watchdog probe).
- await aiAgentService.releaseOperationLock(operationId, stepLockOwner);
- }
+ // next step ready and the deadline allows (see `runStepInvocation`).
+ const { currentStepIndex, inlinedSteps, result } = await runStepInvocation(
+ aiAgentService,
+ coordinator,
+ {
+ approvedToolCall,
+ asyncToolVerifyAttempt,
+ clientLlmWaitExpired,
+ context,
+ // The fallback stands in for the queue's redelivery of an inline step 0
+ // that did not settle, so it replays like one (see the check above).
+ externalRetryCount: firstStepFallback
+ ? Math.max(1, externalRetryCount)
+ : externalRetryCount,
+ finishAfterAsyncTool,
+ firstStepDispatch: firstStepFallback ? 'inline_fallback' : undefined,
+ groupMemberTimeout,
+ humanInput,
+ lockRetryAttempt,
+ operationId,
+ rejectAndContinue,
+ rejectionReason,
+ resumeAsyncTool,
+ resumeClientLlm,
+ stepIndex,
+ toolMessageId,
+ verifyAsyncToolBarrier,
+ },
+ {
+ invocationDeadlineAt: startTime + STEP_INVOCATION_MAX_DURATION_MS,
+ stepStartDeadlineAt: startTime + INLINE_STEP_START_DEADLINE_MS,
+ },
+ );
// A non-stale lock conflict means another delivery is still executing this
// operation. Once the inline loop has run steps of its own the delivery has
diff --git a/apps/server/src/routers/lambda/aiAgent/exec.ts b/apps/server/src/routers/lambda/aiAgent/exec.ts
index e3f6cc49dac..8703f21d11c 100644
--- a/apps/server/src/routers/lambda/aiAgent/exec.ts
+++ b/apps/server/src/routers/lambda/aiAgent/exec.ts
@@ -210,6 +210,8 @@ export const bridgeLegacyResumeToSourceIntervention = async (
export const execRouter = router({
execAgent: aiAgentWriteProcedure.input(ExecAgentSchema).mutation(async ({ input, ctx }) => {
+ // The clock an inline step 0 (`agent_inline_first_step`) budgets against.
+ const requestStartedAt = Date.now();
const {
agentId,
slug,
@@ -284,6 +286,8 @@ export const execRouter = router({
...request,
acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),
+ // Only this route offers to run step 0 itself: it knows its own clock.
+ inlineFirstStep: { requestStartedAt },
// A non-superseding start waits on the surface like a server-started
// follow-up, so a thread's live run is refused as well.
...(supersedeLiveRun ? {} : { queuedSuccessor: true }),
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts
index 551528d8a81..0bd51c1d352 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { hookDispatcher } from '../../hooks';
import { type OperationCreationParams } from '../../types';
import { AgentRuntimeService } from '..';
+import { INLINE_FIRST_STEP_FALLBACK_DELAY_MS } from '../constants';
import { setUpService } from './testUtils';
vi.mock('@lobechat/model-runtime', (...args) =>
@@ -197,6 +198,38 @@ describe('AgentRuntimeService', () => {
);
});
+ it('queues step 0 right away when nothing runs it inline', async () => {
+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
+ (service as any).queueService = { scheduleMessage };
+
+ await service.createOperation({ ...mockParams, pendingInitRequest: { prompt: 'hi' } as any });
+
+ const message = scheduleMessage.mock.calls[0][0];
+ expect(message.delay).toBe(50);
+ expect(message).not.toHaveProperty('payload');
+ });
+
+ it('still queues an inline step 0, later and marked as its fallback', async () => {
+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
+ (service as any).queueService = { scheduleMessage };
+
+ const result = await service.createOperation({
+ ...mockParams,
+ inlineFirstStep: true,
+ pendingInitRequest: { prompt: 'hi' } as any,
+ });
+
+ expect(result.autoStarted).toBe(true);
+ expect(scheduleMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ delay: INLINE_FIRST_STEP_FALLBACK_DELAY_MS,
+ endpoint: expect.stringMatching(/\/run$/),
+ payload: { inlineFirstStepFallback: true },
+ stepIndex: 0,
+ }),
+ );
+ });
+
it('mirrors a resumed LLM-call baseline into the usage counter old workers report', async () => {
await service.createOperation({ ...mockParams, autoStart: false, initialLlmCalls: 7 });
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.inlineFirstStep.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.inlineFirstStep.test.ts
new file mode 100644
index 00000000000..12de6271e26
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.inlineFirstStep.test.ts
@@ -0,0 +1,235 @@
+/**
+ * @vitest-environment node
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { hookDispatcher } from '../../hooks';
+import { type AgentExecutionParams } from '../../types';
+import { AgentRuntimeService } from '..';
+import { stubRunningDurableOperation } from './testUtils';
+
+vi.mock('@lobechat/model-runtime', (...args) =>
+ import('./testUtils').then((m) =>
+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),
+ ),
+);
+
+const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));
+
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));
+
+// Mock trusted client to avoid server-side env access
+vi.mock('@/libs/trusted-client', (...args) =>
+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),
+);
+
+// Mock database and models
+vi.mock('@/server/services/file', (...args) =>
+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),
+);
+
+vi.mock('@/database/models/message', (...args) =>
+ import('./testUtils').then((m) =>
+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),
+ ),
+);
+
+vi.mock('@/database/models/agent', (...args) =>
+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),
+);
+
+vi.mock('@/database/models/plugin', (...args) =>
+ import('./testUtils').then((m) =>
+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),
+ ),
+);
+
+// Mock ModelRuntime to avoid server-side env access
+vi.mock('@/server/modules/ModelRuntime', (...args) =>
+ import('./testUtils').then((m) =>
+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),
+ ),
+);
+
+// Mock search service to avoid server-side env access
+vi.mock('@/server/services/search', (...args) =>
+ import('./testUtils').then((m) =>
+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),
+ ),
+);
+
+// Mock factory and redis dependencies to break env import chains,
+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends
+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>
+ import('./testUtils').then((m) =>
+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),
+ ),
+);
+
+vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>
+ import('./testUtils').then((m) =>
+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),
+ ),
+);
+
+// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports
+vi.mock('@/server/modules/AgentRuntime', (...args) =>
+ import('./testUtils').then((m) =>
+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),
+ ),
+);
+
+// Spread the real module and override only `AgentRuntime` (to stub `.step()`).
+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),
+// so this mock survives future executor migrations without edits.
+vi.mock('@lobechat/agent-runtime', (...args) =>
+ import('./testUtils').then((m) =>
+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),
+ ),
+);
+
+vi.mock('@/server/services/queue', (...args) =>
+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),
+);
+
+// Mock Mecha module
+vi.mock('@/server/modules/Mecha', (...args) =>
+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),
+);
+
+// Mock model-bank
+vi.mock('model-bank', (...args) =>
+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),
+);
+// `agent_inline_first_step`: the inline run and its queued fallback both reach
+// step 0 through `executeStep`, so what they must share with an ordinary queue
+// delivery (the claim, Stop) and what they add (the dispatch record, the
+// fallback's marker on a re-queue) is checked here against the real
+// coordinator and its in-memory lock.
+describe('executeStep for an inline step 0', () => {
+ const mockDb: any = { delete: vi.fn(), insert: vi.fn(), select: vi.fn(), update: vi.fn() };
+ const operationId = 'test-operation-1';
+ const placeholder = { phase: 'user_input', session: { sessionId: operationId, stepCount: 0 } };
+
+ const pendingState = () => ({
+ createdAt: new Date(Date.now() - 1500).toISOString(),
+ events: [],
+ lastModified: new Date().toISOString(),
+ messages: [],
+ operationId,
+ origin: { agentId: 'agent-1', topicId: 'topic-1' },
+ request: { approvedToolEntries: [], selectedToolIds: [] },
+ status: 'running',
+ stepCount: 0,
+ });
+
+ const buildService = (options: Record<string, unknown> = {}) => {
+ const svc = new AgentRuntimeService(mockDb, 'test-user-id', {
+ delegate: { runDeferredInit: vi.fn() },
+ ...options,
+ } as any);
+ const coordinator = (svc as any).coordinator;
+ for (const key of Object.getOwnPropertyNames(Object.getPrototypeOf(coordinator))) {
+ if (key !== 'constructor' && typeof coordinator[key] === 'function') {
+ vi.spyOn(coordinator, key);
+ }
+ }
+ coordinator.loadAgentState.mockResolvedValue(pendingState());
+ return { coordinator, svc };
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ stubRunningDurableOperation();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ hookDispatcher.unregister(operationId);
+ });
+
+ it('settles a run stopped before the inline step started, as the queue worker does', async () => {
+ const { coordinator, svc } = buildService();
+ coordinator.isInterrupted.mockResolvedValue(true);
+ const lifecycle = (svc as any).completionLifecycle;
+ const dispatch = vi.spyOn(lifecycle, 'dispatchHooks').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ const publish = vi.spyOn((svc as any).streamManager, 'publishStreamEvent');
+ const params: AgentExecutionParams = {
+ context: placeholder as any,
+ firstStepDispatch: 'inline',
+ operationId,
+ stepIndex: 0,
+ };
+
+ const result = await svc.executeStep(params);
+
+ expect(result.success).toBe(true);
+ expect(publish).not.toHaveBeenCalledWith(
+ operationId,
+ expect.objectContaining({ type: 'step_start' }),
+ );
+ expect(dispatch).toHaveBeenCalledWith(operationId, expect.anything(), 'interrupted');
+ expect(coordinator.saveAgentState).toHaveBeenCalledWith(
+ operationId,
+ expect.objectContaining({ status: 'interrupted' }),
+ );
+ });
+
+ it('records how the first step was dispatched and how long after creation it started', async () => {
+ const { coordinator, svc } = buildService();
+ coordinator.isInterrupted.mockResolvedValue(true);
+ vi.spyOn((svc as any).completionLifecycle, 'dispatchHooks').mockResolvedValue(undefined);
+ vi.spyOn((svc as any).completionLifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ const info = vi.spyOn(console, 'info').mockImplementation(() => {});
+
+ await svc.executeStep({ firstStepDispatch: 'inline', operationId, stepIndex: 0 });
+
+ const record = info.mock.calls
+ .map(([line]) => {
+ try {
+ return JSON.parse(String(line));
+ } catch {
+ return undefined;
+ }
+ })
+ .find((entry) => entry?.event === 'agent.first_step.start');
+ expect(record).toMatchObject({ dispatch: 'inline', operationId });
+ expect(record.startDelayMs).toBeGreaterThanOrEqual(1500);
+ });
+
+ it('is claimed by one worker at a time: the fallback waits behind the inline run', async () => {
+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
+ const { coordinator, svc } = buildService({
+ queueService: { getImpl: () => ({}), scheduleMessage },
+ });
+ // The inline run holds the operation lock for its step loop.
+ await coordinator.tryClaimStep(operationId, 0, 120, 'inline-owner');
+
+ const result = await svc.executeStep({
+ firstStepDispatch: 'inline_fallback',
+ operationId,
+ stepIndex: 0,
+ });
+
+ expect(result).toMatchObject({ locked: true, lockRescheduled: true });
+ // The re-delivery keeps the marker, so once the inline run settles it is
+ // acknowledged without running the step again.
+ expect(scheduleMessage.mock.calls[0][0]).toMatchObject({
+ payload: { inlineFirstStepFallback: true, lockRetryAttempt: 1 },
+ stepIndex: 0,
+ });
+ });
+
+ it('re-queues an ordinary delivery without the marker', async () => {
+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
+ const { coordinator, svc } = buildService({
+ queueService: { getImpl: () => ({}), scheduleMessage },
+ });
+ await coordinator.tryClaimStep(operationId, 0, 120, 'another-owner');
+
+ await svc.executeStep({ operationId, stepIndex: 0 });
+
+ expect(scheduleMessage.mock.calls[0][0].payload.inlineFirstStepFallback).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts
index 5bd8a87f4fc..436e69cbafe 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts
@@ -66,3 +66,16 @@ export const STEP_LOCK_RETRY_BASE_DELAY_MS = 15_000;
* holds the lock for minutes no longer strands the delivery waiting behind it.
*/
export const STEP_LOCK_RETRY_MAX_DELAY_MS = 120_000;
+
+/**
+ * How long the queued delivery of an inline step 0 waits before it runs.
+ *
+ * It is the fallback for an inline run that never starts or dies: until it
+ * fires, nothing else picks the run up. It is also delivered on every run, and
+ * while the inline run still holds the step it re-queues itself on the lock
+ * backoff (15s, 30s, …), so firing too early costs queue messages. The inline
+ * run normally starts within milliseconds of the response.
+ */
+export const INLINE_FIRST_STEP_FALLBACK_DELAY_MS = Number(
+ process.env.AGENT_INLINE_FIRST_STEP_FALLBACK_DELAY_MS ?? 20_000,
+);
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
index a5378ca9423..1ebfaeee337 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
@@ -13,6 +13,7 @@ import {
type OperationCreationParams,
type OperationCreationResult,
} from '../types';
+import { INLINE_FIRST_STEP_FALLBACK_DELAY_MS } from './constants';
import {
applyOperationInitSlots,
buildPreInitState,
@@ -68,6 +69,7 @@ export async function createOperation(
reservedOperation,
signal,
initialStepCount = 0,
+ inlineFirstStep = false,
} = params;
// Persist initial agent_operations row. CompletionLifecycle owns both
@@ -309,9 +311,11 @@ export async function createOperation(
queueService.scheduleMessage({
context: initialContext,
deduplicationId,
- delay: 50, // Short delay for startup
+ // An inline step 0 normally runs first; this delivery is its fallback.
+ delay: inlineFirstStep ? INLINE_FIRST_STEP_FALLBACK_DELAY_MS : 50,
endpoint: `${deps.baseURL}/run`,
operationId,
+ ...(inlineFirstStep ? { payload: { inlineFirstStepFallback: true } } : {}),
priority: 'high',
retryDelay: queueRetryDelay,
retries: queueRetries,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts
index 3ffeb5a4db3..c2df8f70746 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts
@@ -136,6 +136,7 @@ export async function handleStepLockConflict(
context,
externalRetryCount = 0,
finishAfterAsyncTool,
+ firstStepDispatch,
humanInput,
lockRetryAttempt = 0,
operationId,
@@ -239,6 +240,8 @@ export async function handleStepLockConflict(
approvedToolCall,
finishAfterAsyncTool,
humanInput,
+ // Only the fallback keeps its marker: the inline run never re-queues.
+ inlineFirstStepFallback: firstStepDispatch === 'inline_fallback' || undefined,
lockRetryAttempt: nextLockRetryAttempt,
rejectAndContinue,
rejectionReason,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
index 70cc9bd3dbf..f97de194239 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
@@ -116,6 +116,38 @@ async function assertStepOwnership(
throw new StepOwnershipLostError(operationId, stepIndex, { cause });
}
+/**
+ * Record how an operation's first step reached its worker and how long after
+ * the operation was created it started: the wait the user has between the send
+ * returning and anything happening. One record per operation that starts.
+ */
+function recordFirstStepStart(
+ span: { setAttributes: (attributes: Record<string, number | string>) => unknown },
+ {
+ createdAt,
+ dispatch,
+ operationId,
+ startedAt,
+ }: {
+ createdAt?: string;
+ dispatch: 'inline' | 'inline_fallback' | 'queue';
+ operationId: string;
+ startedAt: number;
+ },
+): void {
+ const createdAtMs = createdAt ? Date.parse(createdAt) : Number.NaN;
+ const startDelayMs = Number.isFinite(createdAtMs) ? startedAt - createdAtMs : undefined;
+ span.setAttributes({
+ 'lobehub.agent_step.first_step_dispatch': dispatch,
+ ...(startDelayMs === undefined
+ ? {}
+ : { 'lobehub.agent_step.first_step_start_delay_ms': startDelayMs }),
+ });
+ console.info(
+ JSON.stringify({ dispatch, event: 'agent.first_step.start', operationId, startDelayMs }),
+ );
+}
+
/**
* Execute Agent step
*/
@@ -128,6 +160,7 @@ export async function executeStep(
stepIndex,
resumeClientLlm,
externalRetryCount = 0,
+ firstStepDispatch,
inlineContinuation = false,
retainStepLock = false,
stepLockOwner: providedStepLockOwner,
@@ -201,6 +234,14 @@ export async function executeStep(
throw new Error(`Agent state not found for operation ${operationId}`);
}
stopRunSlotLease = startRunSlotLease(deps.userId, agentState);
+ if (agentState.stepCount === 0) {
+ recordFirstStepStart(invokeAgentSpan, {
+ createdAt: agentState.createdAt,
+ dispatch: firstStepDispatch ?? 'queue',
+ operationId,
+ startedAt: stepStartAt,
+ });
+ }
// A run created without its init still carries the turn's request: run
// that init here, after the step claim and before anything is published.
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 6d27cccd6bf..ec25085bc7a 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -167,6 +167,14 @@ export interface AgentExecutionParams {
* `tryResumeParentFromAsyncTool({ onComplete: 'finish' })`.
*/
finishAfterAsyncTool?: boolean;
+ /**
+ * How step 0 of an `agent_inline_first_step` run reached this worker: run
+ * inline by the `execAgent` invocation (`inline`), or the queued fallback
+ * delivery published next to it (`inline_fallback`). Absent for every other
+ * delivery. Recorded on the step span; a lock-conflict re-delivery of the
+ * fallback carries it on, so it still checks whether the inline run settled.
+ */
+ firstStepDispatch?: 'inline' | 'inline_fallback';
/**
* Watchdog payload to enforce a group member's timeout: when the member op
* hasn't reached a terminal state by its deadline, interrupt it and bridge a
@@ -580,6 +588,13 @@ export interface OperationCreationParams {
initialMessages?: any[];
/** Initial step count offset for resumed operations (accumulated from previous runs) */
initialStepCount?: number;
+ /**
+ * The caller runs step 0 itself, right after this returns
+ * (`agent_inline_first_step`). The queued delivery of step 0 is still
+ * published, as the fallback for a run that never starts: later, and marked so
+ * it is a no-op once the inline run settled the step.
+ */
+ inlineFirstStep?: boolean;
/**
* Server-authored provenance for a continuation created from a durable human
* intervention claim. It is persisted in both agent_operations.metadata and
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts
index 0b22a4a389d..51190078b34 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts
@@ -7,6 +7,7 @@ import {
buildPreInitState,
pickOperationInitSlots,
} from '@/server/services/agentRuntime/AgentRuntimeService/operationInitSlots';
+import type * as ScheduleAfterResponseModule from '@/server/utils/scheduleAfterResponse';
import { AiAgentService } from '../index';
import type * as OperationInitModule from '../pipeline/operationInit';
@@ -23,7 +24,9 @@ const {
mockAppEnv,
mockFeatureFlags,
mockTopicFindById,
+ mockAfterUnscoped,
} = vi.hoisted(() => ({
+ mockAfterUnscoped: vi.fn(),
mockAppEnv: {} as Record<string, unknown>,
mockFeatureFlags: vi.fn(),
mockCreateOperation: vi.fn(),
@@ -45,6 +48,12 @@ vi.mock('@/envs/app', async (importOriginal) => {
};
});
+// Captures the post-response hand-off of an inline step 0 without running it.
+vi.mock('@/server/utils/scheduleAfterResponse', async (importOriginal) => {
+ const actual = await importOriginal<typeof ScheduleAfterResponseModule>();
+ return { ...actual, afterUnscoped: mockAfterUnscoped };
+});
+
vi.mock('@/server/featureFlags', () => ({
getServerFeatureFlagsStateFromRuntimeConfig: mockFeatureFlags,
}));
@@ -435,6 +444,83 @@ describe('AiAgentService.runDeferredInit - parity with the send path', () => {
expect(runOperationInit).toHaveBeenCalledTimes(1);
expect(mockCreateOperation.mock.calls[0][0].pendingInitRequest).toBeUndefined();
});
+
+ describe('agent_inline_first_step', () => {
+ const route = { inlineFirstStep: { requestStartedAt: Date.now() } };
+
+ it('leaves step 0 to the queue while the flag is off', async () => {
+ await service.execAgent({ ...plainSend, ...route });
+
+ expect(mockCreateOperation.mock.calls[0][0].inlineFirstStep).toBe(false);
+ expect(mockAfterUnscoped).not.toHaveBeenCalled();
+ });
+
+ it('runs step 0 after the response once the flag is on', async () => {
+ mockFeatureFlags.mockResolvedValue({
+ enableDeferredInit: true,
+ enableInlineFirstStep: true,
+ });
+
+ const result = await service.execAgent({ ...plainSend, ...route });
+
+ expect(result.success).toBe(true);
+ expect(mockCreateOperation.mock.calls[0][0].inlineFirstStep).toBe(true);
+ expect(mockAfterUnscoped).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails closed when the flag cannot be read', async () => {
+ mockFeatureFlags
+ .mockResolvedValueOnce({ enableDeferredInit: true })
+ .mockRejectedValueOnce(new Error('edge config down'));
+
+ await service.execAgent({ ...plainSend, ...route });
+
+ expect(mockCreateOperation.mock.calls[0][0].pendingInitRequest).toBeDefined();
+ expect(mockCreateOperation.mock.calls[0][0].inlineFirstStep).toBe(false);
+ expect(mockAfterUnscoped).not.toHaveBeenCalled();
+ });
+
+ it('keeps step 0 on the queue for a caller that did not ask for it', async () => {
+ mockFeatureFlags.mockResolvedValue({
+ enableDeferredInit: true,
+ enableInlineFirstStep: true,
+ });
+
+ await service.execAgent(plainSend);
+
+ expect(mockCreateOperation.mock.calls[0][0].inlineFirstStep).toBe(false);
+ expect(mockAfterUnscoped).not.toHaveBeenCalled();
+ });
+
+ it('keeps step 0 on the queue for a send that runs its init on the send path', async () => {
+ mockFeatureFlags.mockResolvedValue({
+ enableDeferredInit: true,
+ enableInlineFirstStep: true,
+ });
+
+ await service.execAgent({ ...plainSend, ...route, autoStart: false });
+
+ expect(mockCreateOperation.mock.calls[0][0].pendingInitRequest).toBeUndefined();
+ expect(mockCreateOperation.mock.calls[0][0].inlineFirstStep).toBe(false);
+ expect(mockAfterUnscoped).not.toHaveBeenCalled();
+ });
+
+ it('does not run a step the queue was never handed', async () => {
+ mockFeatureFlags.mockResolvedValue({
+ enableDeferredInit: true,
+ enableInlineFirstStep: true,
+ });
+ mockCreateOperation.mockResolvedValueOnce({
+ autoStarted: false,
+ operationId: 'op-123',
+ success: true,
+ });
+
+ await service.execAgent({ ...plainSend, ...route });
+
+ expect(mockAfterUnscoped).not.toHaveBeenCalled();
+ });
+ });
});
describe('a share visitor run', () => {
diff --git a/apps/server/src/services/aiAgent/composerRun.ts b/apps/server/src/services/aiAgent/composerRun.ts
index a0f76669d4b..5ec65ec4553 100644
--- a/apps/server/src/services/aiAgent/composerRun.ts
+++ b/apps/server/src/services/aiAgent/composerRun.ts
@@ -27,6 +27,7 @@ export type ComposerRunRequest = Pick<
| 'existingMessageIds'
| 'fileIds'
| 'includeFinalState'
+ | 'inlineFirstStep'
| 'llmExecutor'
| 'localDeviceId'
| 'mentionedAgents'
@@ -119,6 +120,7 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR
},
clientProtocol: input.clientProtocol,
includeFinalState: input.includeFinalState,
+ inlineFirstStep: input.inlineFirstStep,
llmExecutor: input.llmExecutor,
// This path serves the composer (`aiAgentService.execAgentTask`).
// The client already queues follow-ups behind a live run and shows the
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 3f98dbff69a..77b9a15ec49 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -39,6 +39,7 @@ import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
import { TopicRepository } from '@/database/repositories/topic';
+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';
import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
import { AgentService } from '@/server/services/agent';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
@@ -59,6 +60,7 @@ import { ComposioService } from '@/server/services/composio';
import { DocumentService } from '@/server/services/document';
import { MarketService } from '@/server/services/market';
import type { SteerQueueScope } from '@/server/services/redis/steerQueue';
+import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
import {
type BackgroundSubAgentResult,
@@ -66,6 +68,7 @@ import {
} from './backgroundSubAgentDelivery';
import { resolveForegroundInterventionConfig } from './foregroundIntervention';
import { createGraphAwareAgentFactory } from './helpers/agentFactory';
+import { type InlineFirstStepRun, runInlineFirstStep } from './inlineFirstStep';
import { InterventionController } from './intervention/InterventionController';
import type { ApprovalClaimState } from './pipeline/approvalResume';
import { runDeferredOperationInit } from './pipeline/deferredInit';
@@ -255,6 +258,7 @@ export class AiAgentService {
resolveSourceAgentSnapshot: (agentId, sourceOperationId) =>
this.resolveSourceAgentSnapshot(agentId, sourceOperationId),
retirePendingApprovalOperation: (opId) => this.retirePendingApprovalOperation(opId),
+ scheduleInlineFirstStep: (run) => this.scheduleInlineFirstStep(run),
topicModel: this.topicModel,
userId: this.userId,
withholdGatewayToken: this.withholdGatewayToken,
@@ -262,6 +266,29 @@ export class AiAgentService {
};
}
+ /**
+ * Hand step 0 to the host to run once the response is sent
+ * (`agent_inline_first_step`). Unscoped: a step's own deferred work must not
+ * join the clock of whatever scope the send ran in.
+ */
+ private scheduleInlineFirstStep(run: InlineFirstStepRun): void {
+ afterUnscoped(() =>
+ runInlineFirstStep(
+ {
+ coordinator: new AgentRuntimeCoordinator(),
+ // Built the way the step worker (`/api/agent/run`) builds it, from the
+ // run's metadata, so the step sees the same service there and here.
+ createService: (metadata) =>
+ new AiAgentService(this.db, metadata.userId, {
+ includeShareVisitor: Boolean(metadata.streamOwnerUserId),
+ workspaceId: metadata.workspaceId,
+ }),
+ },
+ run,
+ ),
+ );
+ }
+
/** Dependency bundle for the topic-start stage in `pipeline/topicStart.ts`. */
private get topicStartDeps(): TopicStartDeps {
return {
diff --git a/apps/server/src/services/aiAgent/inlineFirstStep.test.ts b/apps/server/src/services/aiAgent/inlineFirstStep.test.ts
new file mode 100644
index 00000000000..9996ef4f9e6
--- /dev/null
+++ b/apps/server/src/services/aiAgent/inlineFirstStep.test.ts
@@ -0,0 +1,299 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getInvocationDeadline } from '@/server/utils/invocationDeadline';
+
+import {
+ INLINE_FIRST_STEP_MAX_DURATION_MS,
+ INLINE_FIRST_STEP_START_DEADLINE_MS,
+ type InlineFirstStepDeps,
+ isInlineFirstStepEnabled,
+ runInlineFirstStep,
+ shouldRunFirstStepInline,
+} from './inlineFirstStep';
+
+const { mockFeatureFlags } = vi.hoisted(() => ({ mockFeatureFlags: vi.fn() }));
+
+vi.mock('@/server/featureFlags', () => ({
+ getServerFeatureFlagsStateFromRuntimeConfig: mockFeatureFlags,
+}));
+
+vi.mock('@/server/services/agentRuntime/opportunisticSweep', () => ({
+ scheduleOpportunisticStaleSweep: vi.fn(),
+ scheduleOpportunisticVerifySweep: vi.fn(),
+}));
+
+const OP = 'op-1';
+const OWNER = 'op-1:owner';
+const placeholderContext = { phase: 'user_input', session: { sessionId: OP } };
+
+const doneResult = () => ({
+ nextStepScheduled: false,
+ state: { status: 'done', stepCount: 1 },
+ success: true,
+});
+
+/**
+ * An operation lock with the claim semantics the queue worker relies on: one
+ * owner at a time, re-entrant for that owner.
+ */
+const createLock = () => {
+ let holder: string | undefined;
+ return {
+ claim: (owner: string) => {
+ if (holder && holder !== owner) return false;
+ holder = owner;
+ return true;
+ },
+ get holder() {
+ return holder;
+ },
+ release: (owner: string) => {
+ if (holder === owner) holder = undefined;
+ },
+ };
+};
+
+const setup = (
+ state: Record<string, unknown> | null = { initialContext: placeholderContext, stepCount: 0 },
+) => {
+ const lock = createLock();
+ const settled = new Set<string>();
+ const service = {
+ createOperationLockOwner: vi.fn(() => OWNER),
+ executeStep: vi.fn(async (params: { stepLockOwner?: string }) => {
+ // The step claims the lock itself, exactly as a queue delivery does.
+ if (!lock.claim(params.stepLockOwner!)) return { locked: true, state: {}, success: false };
+ return doneResult();
+ }),
+ releaseOperationLock: vi.fn(async (_operationId: string, owner: string) => lock.release(owner)),
+ scheduleContinuation: vi.fn(async () => {}),
+ };
+ const coordinator = {
+ clearInlineResume: vi.fn(async () => {}),
+ getOperationMetadata: vi.fn(async () => ({ userId: 'user-1', workspaceId: 'ws-1' })),
+ loadAgentState: vi.fn(async () => state),
+ loadInlineResume: vi.fn(async () => null),
+ markInlineFirstStepSettled: vi.fn(async (operationId: string) => {
+ settled.add(operationId);
+ }),
+ tryClaimStep: vi.fn(
+ async (_operationId: string, _stepIndex: number, _ttl?: number, owner?: string) =>
+ lock.claim(owner!),
+ ),
+ };
+ const createService = vi.fn(() => service);
+ const deps = { coordinator, createService } as unknown as InlineFirstStepDeps;
+
+ /** The queued fallback delivery, as `/api/agent/run` treats it. */
+ const queuedDelivery = async () => {
+ if (settled.has(OP)) return 'noop' as const;
+ const owner = 'queue:owner';
+ const result = await service.executeStep({ stepLockOwner: owner } as any);
+ lock.release(owner);
+ return result.locked ? ('locked' as const) : ('ran' as const);
+ };
+
+ return { coordinator, createService, deps, lock, queuedDelivery, service, settled };
+};
+
+describe('shouldRunFirstStepInline', () => {
+ const enabled = () => Promise.resolve(true);
+ const input = { deferredInit: true, requestStartedAt: 1, stepIndex: 0 };
+
+ it('runs a deferred-init send that the route opted in, when the flag is on', async () => {
+ await expect(shouldRunFirstStepInline(input, enabled)).resolves.toBe(true);
+ });
+
+ it.each([
+ ['the init ran on the send path', { deferredInit: false }],
+ ['no route asked for it', { requestStartedAt: undefined }],
+ ['the run does not start at step 0', { stepIndex: 3 }],
+ ])('keeps step 0 on the queue when %s', async (_label, override) => {
+ const isEnabled = vi.fn(enabled);
+
+ await expect(shouldRunFirstStepInline({ ...input, ...override }, isEnabled)).resolves.toBe(
+ false,
+ );
+ expect(isEnabled).not.toHaveBeenCalled();
+ });
+
+ it('keeps step 0 on the queue when the flag is off or unreadable', async () => {
+ mockFeatureFlags.mockResolvedValueOnce({ enableInlineFirstStep: false });
+ await expect(
+ shouldRunFirstStepInline(input, () => isInlineFirstStepEnabled('u')),
+ ).resolves.toBe(false);
+
+ mockFeatureFlags.mockRejectedValueOnce(new Error('edge config down'));
+ await expect(
+ shouldRunFirstStepInline(input, () => isInlineFirstStepEnabled('u')),
+ ).resolves.toBe(false);
+ });
+});
+
+describe('runInlineFirstStep', () => {
+ const run = { operationId: OP, requestStartedAt: Date.now(), stepIndex: 0 };
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('runs step 0 once under the step claim, and the queued delivery is then a no-op', async () => {
+ const { coordinator, deps, lock, queuedDelivery, service } = setup();
+
+ await expect(runInlineFirstStep(deps, run)).resolves.toBe('ran');
+
+ expect(coordinator.tryClaimStep).toHaveBeenCalledWith(OP, 0, expect.any(Number), OWNER);
+ expect(service.executeStep).toHaveBeenCalledTimes(1);
+ expect(service.executeStep).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context: placeholderContext,
+ firstStepDispatch: 'inline',
+ operationId: OP,
+ retainStepLock: true,
+ stepIndex: 0,
+ stepLockOwner: OWNER,
+ }),
+ );
+ expect(coordinator.markInlineFirstStepSettled).toHaveBeenCalledWith(OP);
+ expect(lock.holder).toBeUndefined();
+
+ await expect(queuedDelivery()).resolves.toBe('noop');
+ expect(service.executeStep).toHaveBeenCalledTimes(1);
+ });
+
+ it('builds the step service from the run metadata, not the send', async () => {
+ const { createService, deps } = setup();
+
+ await runInlineFirstStep(deps, run);
+
+ expect(createService).toHaveBeenCalledWith({
+ streamOwnerUserId: undefined,
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('is a no-op when the queued delivery claimed the step first', async () => {
+ const { coordinator, deps, lock, service } = setup();
+ lock.claim('queue:owner');
+
+ await expect(runInlineFirstStep(deps, run)).resolves.toBe('claim_lost');
+
+ expect(service.executeStep).not.toHaveBeenCalled();
+ expect(coordinator.markInlineFirstStepSettled).not.toHaveBeenCalled();
+ // The queue's claim is untouched.
+ expect(lock.holder).toBe('queue:owner');
+ });
+
+ it('is a no-op when the queued delivery already ran the step', async () => {
+ const { coordinator, deps, lock, service } = setup({ stepCount: 1 });
+
+ await expect(runInlineFirstStep(deps, run)).resolves.toBe('already_ran');
+
+ expect(service.executeStep).not.toHaveBeenCalled();
+ expect(coordinator.markInlineFirstStepSettled).not.toHaveBeenCalled();
+ expect(lock.holder).toBeUndefined();
+ });
+
+ it('leaves a run without runtime metadata to the queued delivery', async () => {
+ const { coordinator, deps, service } = setup();
+ coordinator.getOperationMetadata.mockResolvedValueOnce(null as any);
+
+ await expect(runInlineFirstStep(deps, run)).resolves.toBe('missing_operation');
+
+ expect(coordinator.tryClaimStep).not.toHaveBeenCalled();
+ expect(service.executeStep).not.toHaveBeenCalled();
+ });
+
+ it('leaves a failed step to the queued delivery as its redelivery', async () => {
+ const { coordinator, deps, lock, queuedDelivery, service } = setup();
+ service.executeStep.mockRejectedValueOnce(new Error('durable status unavailable'));
+
+ await expect(runInlineFirstStep(deps, run)).resolves.toBe('failed');
+
+ expect(coordinator.markInlineFirstStepSettled).not.toHaveBeenCalled();
+ expect(lock.holder).toBeUndefined();
+ await expect(queuedDelivery()).resolves.toBe('ran');
+ });
+
+ it('runs a stopped run through the step, which settles the stop', async () => {
+ // Stop pressed between the response and the inline start: the run is
+ // already interrupted, and `executeStep` settles it without a step.
+ const { deps, service } = setup({
+ initialContext: placeholderContext,
+ status: 'interrupted',
+ stepCount: 0,
+ });
+ service.executeStep.mockResolvedValueOnce({
+ nextStepScheduled: false,
+ state: { status: 'interrupted', stepCount: 0 },
+ stepResult: null,
+ success: true,
+ } as any);
+
+ await expect(runInlineFirstStep(deps, run)).resolves.toBe('ran');
+
+ expect(service.executeStep).toHaveBeenCalledTimes(1);
+ expect(service.scheduleContinuation).not.toHaveBeenCalled();
+ });
+
+ describe('time budget', () => {
+ const continuation = (stepIndex: number) => ({
+ context: { phase: 'llm_result' },
+ operationId: OP,
+ stepIndex,
+ });
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(1_000_000);
+ });
+
+ it('keeps stepping inline while the deadline allows', async () => {
+ const { deps, service } = setup();
+ service.executeStep
+ .mockResolvedValueOnce({ continuation: continuation(1), state: {}, success: true } as any)
+ .mockResolvedValueOnce(doneResult() as any);
+
+ await runInlineFirstStep(deps, { ...run, requestStartedAt: Date.now() });
+
+ expect(service.executeStep).toHaveBeenCalledTimes(2);
+ expect(service.executeStep).toHaveBeenLastCalledWith(
+ expect.not.objectContaining({ firstStepDispatch: expect.anything() }),
+ );
+ expect(service.scheduleContinuation).not.toHaveBeenCalled();
+ });
+
+ it('hands the next step to the queue once the deadline has passed', async () => {
+ const { coordinator, deps, service } = setup();
+ const requestStartedAt = Date.now();
+ service.executeStep.mockImplementationOnce(async () => {
+ // Step 0 ran past the point at which another step may start.
+ vi.setSystemTime(requestStartedAt + INLINE_FIRST_STEP_START_DEADLINE_MS);
+ return { continuation: continuation(1), state: {}, success: true } as any;
+ });
+
+ await expect(runInlineFirstStep(deps, { ...run, requestStartedAt })).resolves.toBe('ran');
+
+ expect(service.executeStep).toHaveBeenCalledTimes(1);
+ expect(service.scheduleContinuation).toHaveBeenCalledWith(continuation(1));
+ expect(coordinator.clearInlineResume).toHaveBeenCalledWith(OP, OWNER);
+ expect(coordinator.markInlineFirstStepSettled).toHaveBeenCalledWith(OP);
+ });
+
+ it('sizes long waits inside the step to the execAgent route, not the worker route', async () => {
+ const { deps, service } = setup();
+ const requestStartedAt = Date.now();
+ let deadline: number | undefined;
+ service.executeStep.mockImplementationOnce(async () => {
+ deadline = getInvocationDeadline();
+ return doneResult() as any;
+ });
+
+ await runInlineFirstStep(deps, { ...run, requestStartedAt });
+
+ expect(deadline).toBe(requestStartedAt + INLINE_FIRST_STEP_MAX_DURATION_MS);
+ });
+ });
+});
diff --git a/apps/server/src/services/aiAgent/inlineFirstStep.ts b/apps/server/src/services/aiAgent/inlineFirstStep.ts
new file mode 100644
index 00000000000..a8d2915a9df
--- /dev/null
+++ b/apps/server/src/services/aiAgent/inlineFirstStep.ts
@@ -0,0 +1,222 @@
+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';
+import { SpanStatusCode } from '@lobechat/observability-otel/api';
+import { tracer as agentRuntimeTracer } from '@lobechat/observability-otel/modules/agent-runtime';
+import debug from 'debug';
+
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+import type { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';
+import { STEP_LOCK_TTL_SECONDS } from '@/server/services/agentRuntime/AgentRuntimeService/constants';
+import {
+ scheduleOpportunisticStaleSweep,
+ scheduleOpportunisticVerifySweep,
+} from '@/server/services/agentRuntime/opportunisticSweep';
+
+import { runStepInvocation, type StepInvocationService } from './stepInvocation';
+
+const log = debug('lobe-server:agent:inline-first-step');
+
+/**
+ * When the host kills the `execAgent` invocation, counted from the request.
+ *
+ * `execAgent` is served by the tRPC lambda route, which declares no
+ * `maxDuration` of its own and so runs under the deployment's default, not the
+ * 600s the step worker (`/api/agent/run`) budgets for. 300s is the Vercel
+ * default; set this to the deployment's real limit when it differs.
+ */
+export const INLINE_FIRST_STEP_MAX_DURATION_MS = Number(
+ process.env.AGENT_INLINE_FIRST_STEP_MAX_DURATION_MS ?? 300_000,
+);
+
+/**
+ * Latest point in the `execAgent` invocation at which another step may START,
+ * counted from the request. Step 0 always starts (a second or two in); later
+ * steps run inline only while this allows and are handed to the queue after,
+ * exactly as the step worker does with its own deadline. The headroom to
+ * {@link INLINE_FIRST_STEP_MAX_DURATION_MS} has to cover one long LLM step.
+ */
+export const INLINE_FIRST_STEP_START_DEADLINE_MS = Number(
+ process.env.AGENT_INLINE_FIRST_STEP_DEADLINE_MS ?? 120_000,
+);
+
+/** A flag that cannot be read keeps step 0 on the queue. */
+export const isInlineFirstStepEnabled = async (userId: string): Promise<boolean> => {
+ const flags = await getServerFeatureFlagsStateFromRuntimeConfig(userId).catch(() => undefined);
+ return flags?.enableInlineFirstStep === true;
+};
+
+export interface InlineFirstStepGateInput {
+ /** Whether this send left its init to step 0 (`shouldDeferOperationInit`). */
+ deferredInit: boolean;
+ /**
+ * The route serving the send asked for it and said when its request started.
+ * Only `aiAgent.execAgent` does: other callers run inside invocations whose
+ * clock they do not know (a step worker draining a queued follow-up, a bot
+ * webhook) or are not a person waiting at the composer.
+ */
+ requestStartedAt?: number;
+ /** The run's first step index. A deferred init always starts at 0. */
+ stepIndex: number;
+}
+
+/**
+ * Only a send that deferred its init runs step 0 inline. That gate already
+ * limits it to a plain chat send on the queue runtime with auto-start: no
+ * orchestration (bots, group members, sub-agents, evals, share visitors,
+ * reserved or continuation operations), no resume or approval, no fixed or
+ * required device.
+ *
+ * The flag is read last, so runs that could never inline pay no read for it.
+ */
+export const shouldRunFirstStepInline = async (
+ { deferredInit, requestStartedAt, stepIndex }: InlineFirstStepGateInput,
+ isEnabled: () => Promise<boolean>,
+): Promise<boolean> =>
+ deferredInit &&
+ requestStartedAt !== undefined &&
+ stepIndex === 0 &&
+ (await isEnabled().catch(() => false));
+
+export interface InlineFirstStepRun {
+ operationId: string;
+ /** When the `execAgent` request started, in epoch ms: the invocation's clock. */
+ requestStartedAt: number;
+ stepIndex: number;
+}
+
+/** What became of an inline step 0. */
+export type InlineFirstStepOutcome =
+ /** The queued delivery already ran the step before the inline run got to it. */
+ | 'already_ran'
+ /** The queued delivery holds the step; it runs it. */
+ | 'claim_lost'
+ /** The step loop threw; the queued delivery stands in for the redelivery. */
+ | 'failed'
+ /** No runtime metadata or state: the queued delivery settles the run as the worker does. */
+ | 'missing_operation'
+ | 'ran';
+
+export interface InlineFirstStepDeps {
+ coordinator: Pick<
+ AgentRuntimeCoordinator,
+ | 'clearInlineResume'
+ | 'getOperationMetadata'
+ | 'loadAgentState'
+ | 'loadInlineResume'
+ | 'markInlineFirstStepSettled'
+ | 'tryClaimStep'
+ >;
+ /**
+ * The service the step runs through, built from the operation's runtime
+ * metadata exactly as the step worker builds it — never the one that served
+ * the send, whose request-scoped options do not belong to the run.
+ */
+ createService: (metadata: {
+ streamOwnerUserId?: string;
+ userId: string;
+ workspaceId?: string;
+ }) => StepInvocationService;
+}
+
+/**
+ * Run step 0 of a just-created operation in the `execAgent` invocation, after
+ * its response, instead of waiting for the queue to deliver it.
+ *
+ * It takes the same operation lock a queue delivery takes, before anything
+ * else, so it and the queued fallback delivery cannot both run the step:
+ * whichever claims first runs it, and the other finds it held or already run.
+ * Once the step loop returns, it marks the step settled, which turns the
+ * fallback into a no-op. When it throws (a lost lock, an unreadable durable
+ * status, a Review that failed to persist), the marker is not written and the
+ * fallback runs as the queue's redelivery of step 0 would.
+ *
+ * The step itself is the worker's `executeStep`, so Stop, a failed deferred
+ * init and a revoked share behave exactly as they do there. Never rejects.
+ */
+export const runInlineFirstStep = (
+ deps: InlineFirstStepDeps,
+ { operationId, requestStartedAt, stepIndex }: InlineFirstStepRun,
+): Promise<InlineFirstStepOutcome> =>
+ agentRuntimeTracer.startActiveSpan('agent.inline_first_step', async (span) => {
+ const { coordinator } = deps;
+ span.setAttributes({
+ 'lobehub.agent_step.operation_id': operationId,
+ 'lobehub.agent_step.since_request_ms': Date.now() - requestStartedAt,
+ });
+ const finish = (outcome: InlineFirstStepOutcome) => {
+ span.setAttribute('lobehub.agent_step.inline_first_step_outcome', outcome);
+ log('[%s] inline step %d: %s', operationId, stepIndex, outcome);
+ return outcome;
+ };
+
+ try {
+ // The step worker rides every delivery to run these background repairs;
+ // a run that finishes inline may never reach that worker.
+ scheduleOpportunisticStaleSweep();
+ scheduleOpportunisticVerifySweep();
+
+ const metadata = await coordinator.getOperationMetadata(operationId);
+ if (!metadata?.userId) return finish('missing_operation');
+
+ const service = deps.createService({
+ streamOwnerUserId: metadata.streamOwnerUserId,
+ userId: metadata.userId,
+ workspaceId: metadata.workspaceId,
+ });
+ const stepLockOwner = service.createOperationLockOwner(operationId);
+ const claimed = await coordinator.tryClaimStep(
+ operationId,
+ stepIndex,
+ STEP_LOCK_TTL_SECONDS,
+ stepLockOwner,
+ );
+ // Not `executeStep`'s own claim: on a conflict it re-queues the delivery,
+ // and here the conflict means the queued delivery already owns the step.
+ if (!claimed) return finish('claim_lost');
+
+ let handedToLoop = false;
+ try {
+ const state = await coordinator.loadAgentState(operationId);
+ if (!state) return finish('missing_operation');
+ // Ran and released before this run started; running it again here
+ // would only publish a stray `step_start` before the stale-step guard.
+ if (state.stepCount > stepIndex) return finish('already_ran');
+
+ handedToLoop = true;
+ const { inlinedSteps, result } = await runStepInvocation(
+ service,
+ coordinator,
+ {
+ // What the queued delivery carries: the placeholder saved on the state.
+ context: (state as AgentState & { initialContext?: AgentRuntimeContext })
+ .initialContext,
+ firstStepDispatch: 'inline',
+ operationId,
+ stepIndex,
+ },
+ {
+ invocationDeadlineAt: requestStartedAt + INLINE_FIRST_STEP_MAX_DURATION_MS,
+ // Bounds the steps after step 0 only: the first one always runs.
+ stepStartDeadlineAt: requestStartedAt + INLINE_FIRST_STEP_START_DEADLINE_MS,
+ },
+ { stepLockOwner },
+ );
+ await coordinator.markInlineFirstStepSettled(operationId);
+
+ span.setAttributes({
+ 'lobehub.agent_step.inlined_steps': inlinedSteps,
+ 'lobehub.agent_step.next_step_queued': Boolean(result.nextStepScheduled),
+ ...(result.state?.status ? { 'lobehub.agent_step.status': result.state.status } : {}),
+ });
+ return finish('ran');
+ } finally {
+ if (!handedToLoop) await service.releaseOperationLock(operationId, stepLockOwner);
+ }
+ } catch (error) {
+ span.recordException(error as Error);
+ span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message });
+ console.error('[inline-first-step] step %d of %s failed: %O', stepIndex, operationId, error);
+ return finish('failed');
+ } finally {
+ span.end();
+ }
+ });
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index e787dba464a..236cc6acfb3 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -25,6 +25,11 @@ import type { ComposioService } from '@/server/services/composio';
import { DocumentService } from '@/server/services/document';
import type { MarketService } from '@/server/services/market';
+import {
+ type InlineFirstStepRun,
+ isInlineFirstStepEnabled,
+ shouldRunFirstStepInline,
+} from '../inlineFirstStep';
import { createRunFacts, type RunFacts } from '../runFacts';
import { applyShareGateToAgentConfig } from '../shareGate';
import { assertAgentRelayHop } from '../sourceAttribution';
@@ -79,6 +84,11 @@ export interface ExecAgentTurnDeps {
sourceOperationId?: string,
) => Promise<AgentSenderMetadata | undefined>;
retirePendingApprovalOperation: (operationId: string) => Promise<void>;
+ /**
+ * Run step 0 of a just-started operation in this invocation, after the
+ * response (`agent_inline_first_step`). Returns at once.
+ */
+ scheduleInlineFirstStep: (run: InlineFirstStepRun) => void;
topicModel: TopicModel;
userId: string;
withholdGatewayToken: boolean;
@@ -705,6 +715,16 @@ export const execAgentTurn = async (
},
() => isDeferredInitEnabled(deps.userId),
);
+ // Such a send may also run its step 0 here, after the response, rather than
+ // wait for the queue to deliver it.
+ const inlineFirstStep = await shouldRunFirstStepInline(
+ {
+ deferredInit: deferInit,
+ requestStartedAt: params.inlineFirstStep?.requestStartedAt,
+ stepIndex: initialStepCount ?? 0,
+ },
+ () => isInlineFirstStepEnabled(deps.userId),
+ );
const init: StartOperationInit = deferInit
? { pendingRequest: toPersistedInitRequest(initRequest) }
: await traceSendStage('operation_init', () =>
@@ -820,6 +840,7 @@ export const execAgentTurn = async (
init,
initialLlmCalls,
initialStepCount,
+ inlineFirstStep,
maxSteps,
operationId,
operationTaskId,
@@ -841,5 +862,12 @@ export const execAgentTurn = async (
},
),
);
+ if (inlineFirstStep && started.success && started.autoStarted && params.inlineFirstStep) {
+ deps.scheduleInlineFirstStep({
+ operationId,
+ requestStartedAt: params.inlineFirstStep.requestStartedAt,
+ stepIndex: initialStepCount ?? 0,
+ });
+ }
return started;
};
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index 1083d5e9fac..78da72d6d09 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -62,6 +62,8 @@ export interface StartOperationInput {
init: StartOperationInit;
initialLlmCalls?: number;
initialStepCount?: number;
+ /** The caller runs step 0 after this returns; see `OperationCreationParams.inlineFirstStep`. */
+ inlineFirstStep?: boolean;
/** Relay executor the calling client declared; lands on `state.host.llmExecutor`. */
llmExecutor?: InternalExecAgentParams['llmExecutor'];
maxSteps?: number;
@@ -138,6 +140,7 @@ export const startOperation = async (
init,
initialLlmCalls,
initialStepCount,
+ inlineFirstStep,
maxSteps,
operationId,
operationTaskId,
@@ -328,6 +331,7 @@ export const startOperation = async (
enableExpertise,
initialLlmCalls,
initialStepCount,
+ inlineFirstStep,
...(providedApprovalResolutionRequestId && approvalSourceOperationId
? {
interventionResolution: {
diff --git a/apps/server/src/services/aiAgent/stepInvocation.ts b/apps/server/src/services/aiAgent/stepInvocation.ts
new file mode 100644
index 00000000000..cdd05c7e0f4
--- /dev/null
+++ b/apps/server/src/services/aiAgent/stepInvocation.ts
@@ -0,0 +1,243 @@
+import debug from 'debug';
+
+import type { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';
+import type {
+ AgentExecutionParams,
+ AgentExecutionResult,
+ AgentStepContinuation,
+} from '@/server/services/agentRuntime/types';
+import { runWithInvocationDeadline } from '@/server/utils/invocationDeadline';
+import {
+ flushScheduledWork,
+ runWithScheduledWorkScope,
+} from '@/server/utils/scheduleAfterResponse';
+
+import type { AiAgentService } from './index';
+
+const log = debug('lobe-server:agent:step-invocation');
+
+/**
+ * Longest the loop waits at a step boundary for work the previous step
+ * deferred with `after()`.
+ *
+ * That work includes settling the step's budget hold, which has to finish
+ * before the next step reserves again. It normally takes well under a second.
+ * The cap only stops one stuck telemetry call from stalling the operation;
+ * anything still running keeps going.
+ */
+export const STEP_BOUNDARY_FLUSH_TIMEOUT_MS = 10_000;
+
+/** What the step loop needs from the service it steps through. */
+export type StepInvocationService = Pick<
+ AiAgentService,
+ 'createOperationLockOwner' | 'executeStep' | 'releaseOperationLock' | 'scheduleContinuation'
+>;
+
+export interface StepInvocationBudget {
+ /**
+ * When the host kills this invocation, in epoch ms: the request's start plus
+ * the route's `maxDuration`.
+ */
+ invocationDeadlineAt: number;
+ /** Latest point, in epoch ms, at which another step may START in this invocation. */
+ stepStartDeadlineAt: number;
+}
+
+/** The delivery a step invocation starts from. */
+export type StepInvocationDelivery = Omit<
+ AgentExecutionParams,
+ 'inlineContinuation' | 'retainStepLock' | 'stepLockOwner'
+>;
+
+export interface StepInvocationResult {
+ /** The step the invocation ran last (or was asked to run). */
+ currentStepIndex: number;
+ /** Steps run after the first one. */
+ inlinedSteps: number;
+ result: AgentExecutionResult;
+}
+
+/**
+ * Run a delivered step, then keep stepping inside this invocation for as long
+ * as the operation has a next step ready and the budget allows, instead of
+ * paying a queue round-trip per step. Whatever is still pending when the budget
+ * runs out goes back to the queue.
+ *
+ * One lock owner spans the whole loop: the operation lock is re-entrant for its
+ * owner, so a redelivery from the queue still loses the race the same way it
+ * does for a single step. Pass `stepLockOwner` when the caller already claimed
+ * the lock with it; the loop releases it either way.
+ *
+ * Shared by the queue worker (`/api/agent/run`) and the inline step 0 of
+ * `execAgent` (`agent_inline_first_step`), so both run steps the same way.
+ */
+export async function runStepInvocation(
+ service: StepInvocationService,
+ coordinator: Pick<AgentRuntimeCoordinator, 'clearInlineResume' | 'loadInlineResume'>,
+ delivery: StepInvocationDelivery,
+ budget: StepInvocationBudget,
+ options: { stepLockOwner?: string } = {},
+): Promise<StepInvocationResult> {
+ const { externalRetryCount, operationId, stepIndex } = delivery;
+
+ const stepLockOwner = options.stepLockOwner ?? service.createOperationLockOwner(operationId);
+ let pendingContinuation: AgentStepContinuation | undefined;
+ let currentStepIndex = stepIndex;
+ let inlinedSteps = 0;
+ let result!: AgentExecutionResult;
+ // True once this invocation has an envelope to account for: either it
+ // resumed from one, or a step handed back a continuation (which parks one).
+ let touchedEnvelope = false;
+
+ // Only a plain "run the next step" delivery may be redirected to a parked
+ // envelope. Anything carrying its own purpose — an approval, a resume, a
+ // watchdog probe — has to run as itself: redirecting it would drop that
+ // payload and silently turn it into an ordinary step. The group-member
+ // timeout is the sharp edge, because it is always scheduled at stepIndex 0
+ // on the member operation, so any envelope at all would swallow it and take
+ // the running loop's recovery pointer down with it.
+ const isPlainStepDelivery =
+ delivery.humanInput === undefined &&
+ delivery.approvedToolCall === undefined &&
+ delivery.rejectionReason === undefined &&
+ delivery.toolMessageId === undefined &&
+ !delivery.rejectAndContinue &&
+ !delivery.resumeAsyncTool &&
+ !delivery.finishAfterAsyncTool &&
+ !delivery.verifyAsyncToolBarrier &&
+ !delivery.resumeClientLlm &&
+ !delivery.clientLlmWaitExpired &&
+ !delivery.groupMemberTimeout;
+
+ try {
+ // A previous invocation may have died part-way through its own inline loop.
+ // It parks the envelope for each step before running it, so an envelope
+ // ahead of the delivered index means exactly that: resume from there. Going
+ // ahead with the delivered index instead would hit the `stepCount >
+ // stepIndex` stale-delivery guard, get ACKed, and strand the operation with
+ // nothing queued behind it.
+ const parked = isPlainStepDelivery
+ ? await coordinator.loadInlineResume<AgentStepContinuation>(operationId)
+ : null;
+ const resumeFrom = parked && parked.stepIndex > stepIndex ? parked : undefined;
+ if (resumeFrom) {
+ log(
+ `[${operationId}] Delivered step ${stepIndex} is behind a parked inline step ${resumeFrom.stepIndex}; resuming there`,
+ );
+ currentStepIndex = resumeFrom.stepIndex;
+ touchedEnvelope = true;
+ }
+
+ // Work a step defers with `after()` (budget settlement, trace flushes,
+ // telemetry) normally waits for the HTTP response. One invocation spans
+ // many steps, so every earlier step's budget hold would stay reserved until
+ // the loop ends and squeeze the next reservation. Scoping it to the loop
+ // starts that work immediately and lets each boundary wait for it, which is
+ // how it behaved when every step was its own request. Long waits inside a
+ // step (a relayed LLM attempt) size themselves to what is left of this
+ // invocation.
+ await runWithInvocationDeadline(budget.invocationDeadlineAt, () =>
+ runWithScheduledWorkScope(async () => {
+ // The first iteration carries this delivery's one-shot payload (human
+ // input, approvals, resume flags). Later iterations are plain steps, so
+ // they must not replay any of it, and neither must a resumed run — it
+ // stands in for a later iteration of a dead loop, not for the original
+ // message.
+ //
+ // `externalRetryCount` is the exception, because it describes this
+ // delivery rather than the step's payload. A parked approval whose Review
+ // failed to persist is only replayed when the count is nonzero, so
+ // dropping it here would leave that approval permanently unavailable.
+ result = resumeFrom
+ ? await service.executeStep({
+ context: resumeFrom.context,
+ externalRetryCount,
+ inlineContinuation: true,
+ operationId,
+ retainStepLock: true,
+ stepIndex: resumeFrom.stepIndex,
+ stepLockOwner,
+ })
+ : await service.executeStep({
+ ...delivery,
+ inlineContinuation: true,
+ retainStepLock: true,
+ stepLockOwner,
+ });
+ pendingContinuation = result.continuation;
+ touchedEnvelope ||= Boolean(pendingContinuation);
+
+ while (pendingContinuation) {
+ // Let the previous step's deferred work finish first. Its budget
+ // hold is released there, and the next step reserves again.
+ const settled = await flushScheduledWork({ timeoutMs: STEP_BOUNDARY_FLUSH_TIMEOUT_MS });
+ if (!settled) {
+ // The deferred work cannot be told apart, so a slow telemetry call
+ // and a slow budget settlement look the same. Reserving again on
+ // top of an unreleased hold is exactly the false "over budget"
+ // this wait exists to prevent, so stop inlining and hand the step
+ // to the queue, the way it ran before steps were inlined.
+ log(
+ `[${operationId}] Deferred work still running after ${STEP_BOUNDARY_FLUSH_TIMEOUT_MS}ms, handing step ${pendingContinuation.stepIndex} back to the queue`,
+ );
+ break;
+ }
+
+ if (Date.now() >= budget.stepStartDeadlineAt) {
+ log(
+ `[${operationId}] Inline budget spent after ${inlinedSteps} extra step(s), handing step ${pendingContinuation.stepIndex} back to the queue`,
+ );
+ break;
+ }
+
+ const next = pendingContinuation;
+ pendingContinuation = undefined;
+ currentStepIndex = next.stepIndex;
+
+ result = await service.executeStep({
+ context: next.context,
+ inlineContinuation: true,
+ operationId,
+ retainStepLock: true,
+ stepIndex: next.stepIndex,
+ stepLockOwner,
+ });
+ inlinedSteps += 1;
+ pendingContinuation = result.continuation;
+ touchedEnvelope ||= Boolean(pendingContinuation);
+
+ // A lock conflict mid-loop means another worker took over this
+ // operation. Stop rather than fight it — that worker owns the rest.
+ if (result.locked) break;
+ }
+
+ // Whatever is still pending goes back to the queue so the operation
+ // resumes in a fresh invocation.
+ if (pendingContinuation) {
+ await service.scheduleContinuation(pendingContinuation);
+ result = { ...result, nextStepScheduled: true };
+ pendingContinuation = undefined;
+ }
+
+ // Drop the envelope once this invocation is done with it: either the queue
+ // owns the next step again, or the operation stopped. Leaving it behind
+ // would let a late redelivery re-run a step someone else already owns.
+ // Skipped when nothing was ever parked, to keep the flag-off path free of
+ // an extra Redis round-trip.
+ //
+ // Scoped to our lock owner, because "done with it" is only true while we
+ // still hold the operation. A delivery that read an envelope and then lost
+ // the lock race must not delete the newer one the live worker parked.
+ if (touchedEnvelope) {
+ await coordinator.clearInlineResume(operationId, stepLockOwner);
+ }
+ }),
+ );
+ } finally {
+ // Owner-scoped, so this is a no-op when the first step never claimed the
+ // lock (a conflicting delivery, a terminal operation, a watchdog probe).
+ await service.releaseOperationLock(operationId, stepLockOwner);
+ }
+
+ return { currentStepIndex, inlinedSteps, result };
+}
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 4b0dfc4b237..0f08d0d085b 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -210,6 +210,13 @@ export interface InternalExecAgentParams extends ExecAgentParams {
initialLlmCalls?: number;
/** Initial step count offset for resumed operations (accumulated from previous runs) */
initialStepCount?: number;
+ /**
+ * Set only by the `aiAgent.execAgent` route: step 0 of a send that defers its
+ * init may run in this invocation after the response (`agent_inline_first_step`).
+ * Carries when the route's request started, the clock its time budget counts
+ * from. Never client-passable.
+ */
+ inlineFirstStep?: { requestStartedAt: number };
/**
* This start came from a person waiting at a composer, not from a background
* producer (task callback, cron, bot, API). Interactive starts serialize only
diff --git a/docs/self-hosting/advanced/feature-flags.mdx b/docs/self-hosting/advanced/feature-flags.mdx
index ae0ed2285a3..1536af2883e 100644
--- a/docs/self-hosting/advanced/feature-flags.mdx
+++ b/docs/self-hosting/advanced/feature-flags.mdx
@@ -34,31 +34,32 @@ You can achieve various feature combinations using the above configuration synta
their default values).
</Callout>
-| Configuration Item | Description | Default Value |
-| --- | --- | --- |
-| `check_updates` | Allows checking for updates. | Enabled |
-| `provider_settings` | Controls model provider settings display. | Enabled |
-| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |
-| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |
-| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |
-| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |
-| `agent_llm_relay` | Runs LLM calls for model providers only the user's device can reach (local Ollama / LM Studio, private-network endpoints) on the client that started the run, while the agent loop stays on the server. Requires an open LobeHub client for such runs. | Disabled |
-| `agent_deferred_init` | Returns a plain chat send as soon as its messages are saved and runs tool discovery and context assembly in the first agent step, so sending feels instant. Requires the queue agent runtime. | Disabled |
-| `agent_deferred_hetero_dispatch` | Returns a plain chat send to a heterogeneous agent (Claude Code, Codex, …) on an online device before the device accepts the run; the dispatch runs after the response, and a failure is shown on the assistant message. | Disabled |
-| `dashboard` | Dashboards: the home and project dashboard pages, the widget Portal, in-chat widget previews and the `builtin-dashboard` agent tool that builds monitoring widgets. When off, these are hidden and the widget / dashboard APIs return FORBIDDEN; widgets already published keep refreshing on their schedule. | Disabled |
-| `mcp_apps` | MCP Apps: a tool result whose MCP server declares an interactive `ui://` view renders that view (the server's HTML, in a sandboxed iframe) in the conversation. When off, such results render as plain tool results and the server does not announce MCP Apps support to MCP servers. | Disabled |
-| `edit_agent` | Allows users to edit assistants. | Enabled |
-| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |
-| `speech_to_text` | Enables speech-to-text functionality. | Enabled |
-| `token_counter` | Reserved for token counter display. | Enabled |
-| `welcome_suggest` | Displays welcome suggestions. | Enabled |
-| `changelog` | Controls changelog modal/page display. | Enabled |
-| `market` | Enables the assistant market functionality. | Enabled |
-| `knowledge_base` | Enables the knowledge base functionality. | Enabled |
-| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |
-| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |
-| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |
-| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |
+| Configuration Item | Description | Default Value |
+| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
+| `check_updates` | Allows checking for updates. | Enabled |
+| `provider_settings` | Controls model provider settings display. | Enabled |
+| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |
+| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |
+| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |
+| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |
+| `agent_llm_relay` | Runs LLM calls for model providers only the user's device can reach (local Ollama / LM Studio, private-network endpoints) on the client that started the run, while the agent loop stays on the server. Requires an open LobeHub client for such runs. | Disabled |
+| `agent_deferred_init` | Returns a plain chat send as soon as its messages are saved and runs tool discovery and context assembly in the first agent step, so sending feels instant. Requires the queue agent runtime. | Disabled |
+| `agent_deferred_hetero_dispatch` | Returns a plain chat send to a heterogeneous agent (Claude Code, Codex, …) on an online device before the device accepts the run; the dispatch runs after the response, and a failure is shown on the assistant message. | Disabled |
+| `agent_inline_first_step` | Runs the first agent step of a plain chat send that uses `agent_deferred_init` in the same server invocation, right after the send returns, instead of waiting for the queue to deliver it; the queued delivery is still sent later as a fallback. Requires the queue agent runtime and `agent_deferred_init`. | Disabled |
+| `dashboard` | Dashboards: the home and project dashboard pages, the widget Portal, in-chat widget previews and the `builtin-dashboard` agent tool that builds monitoring widgets. When off, these are hidden and the widget / dashboard APIs return FORBIDDEN; widgets already published keep refreshing on their schedule. | Disabled |
+| `mcp_apps` | MCP Apps: a tool result whose MCP server declares an interactive `ui://` view renders that view (the server's HTML, in a sandboxed iframe) in the conversation. When off, such results render as plain tool results and the server does not announce MCP Apps support to MCP servers. | Disabled |
+| `edit_agent` | Allows users to edit assistants. | Enabled |
+| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |
+| `speech_to_text` | Enables speech-to-text functionality. | Enabled |
+| `token_counter` | Reserved for token counter display. | Enabled |
+| `welcome_suggest` | Displays welcome suggestions. | Enabled |
+| `changelog` | Controls changelog modal/page display. | Enabled |
+| `market` | Enables the assistant market functionality. | Enabled |
+| `knowledge_base` | Enables the knowledge base functionality. | Enabled |
+| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |
+| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |
+| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |
+| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |
## Interactive Agent Sharing: Deployment and Rollout Boundaries
diff --git a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
index f70a813d2c1..f413cd06948 100644
--- a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
+++ b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
@@ -32,31 +32,32 @@ tags:
关键字,你需要手动控制所有的功能标志(否则它们会采用对应的默认值)。
</Callout>
-| 配置项 | 解释 | 默认值 |
-| --- | --- | --- |
-| `check_updates` | 允许检查更新。 | 开启 |
-| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |
-| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |
-| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |
-| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |
-| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |
-| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |
-| `agent_deferred_init` | 普通聊天发送在消息落库后立即返回,工具发现和上下文组装放到第一个助理步骤中执行,发送不再等待。需要队列模式的助理运行时。 | 关闭 |
-| `agent_deferred_hetero_dispatch` | 普通聊天发给在线设备上的异构助理(Claude Code、Codex 等)时,不等设备接收任务就立即返回;派发在响应后执行,失败会显示在助理消息上。 | 关闭 |
-| `dashboard` | 看板:首页与项目看板页面、监控组件侧边栏、对话内的组件预览,以及用于搭建监控组件的 `builtin-dashboard` 助理工具。关闭时以上入口均隐藏,组件与看板相关接口返回 FORBIDDEN;已发布的组件仍按计划刷新。 | 关闭 |
-| `mcp_apps` | MCP Apps:MCP 服务器为工具结果声明了交互页面(`ui://`)时,在对话中渲染该页面(服务器提供的 HTML,运行在沙箱 iframe 中)。关闭时按普通工具结果显示,服务端也不再向 MCP 服务器声明支持 MCP Apps。 | 关闭 |
-| `edit_agent` | 允许用户编辑助手。 | 开启 |
-| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |
-| `speech_to_text` | 启用语音转文本功能。 | 开启 |
-| `token_counter` | 保留用于令牌计数器显示。 | 开启 |
-| `welcome_suggest` | 显示欢迎建议。 | 开启 |
-| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |
-| `market` | 启用助手市场功能。 | 开启 |
-| `knowledge_base` | 启用知识库功能。 | 开启 |
-| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |
-| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |
-| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |
-| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |
+| 配置项 | 解释 | 默认值 |
+| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --- |
+| `check_updates` | 允许检查更新。 | 开启 |
+| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |
+| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |
+| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |
+| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |
+| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |
+| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |
+| `agent_deferred_init` | 普通聊天发送在消息落库后立即返回,工具发现和上下文组装放到第一个助理步骤中执行,发送不再等待。需要队列模式的助理运行时。 | 关闭 |
+| `agent_deferred_hetero_dispatch` | 普通聊天发给在线设备上的异构助理(Claude Code、Codex 等)时,不等设备接收任务就立即返回;派发在响应后执行,失败会显示在助理消息上。 | 关闭 |
+| `agent_inline_first_step` | 使用 `agent_deferred_init` 的普通聊天发送在返回后,直接在同一次服务端调用中执行第一个助理步骤,不再等待队列投递;队列消息仍会稍后发出作为兜底。需要队列模式的助理运行时和 `agent_deferred_init`。 | 关闭 |
+| `dashboard` | 看板:首页与项目看板页面、监控组件侧边栏、对话内的组件预览,以及用于搭建监控组件的 `builtin-dashboard` 助理工具。关闭时以上入口均隐藏,组件与看板相关接口返回 FORBIDDEN;已发布的组件仍按计划刷新。 | 关闭 |
+| `mcp_apps` | MCP Apps:MCP 服务器为工具结果声明了交互页面(`ui://`)时,在对话中渲染该页面(服务器提供的 HTML,运行在沙箱 iframe 中)。关闭时按普通工具结果显示,服务端也不再向 MCP 服务器声明支持 MCP Apps。 | 关闭 |
+| `edit_agent` | 允许用户编辑助手。 | 开启 |
+| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |
+| `speech_to_text` | 启用语音转文本功能。 | 开启 |
+| `token_counter` | 保留用于令牌计数器显示。 | 开启 |
+| `welcome_suggest` | 显示欢迎建议。 | 开启 |
+| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |
+| `market` | 启用助手市场功能。 | 开启 |
+| `knowledge_base` | 启用知识库功能。 | 开启 |
+| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |
+| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |
+| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |
+| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |
## 交互式助理分享:部署与灰度边界
diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.ts
index 1cdd13a11ee..38d9b053881 100644
--- a/packages/app-config/src/featureFlags/schema.test.ts
+++ b/packages/app-config/src/featureFlags/schema.test.ts
@@ -569,4 +569,20 @@ describe('mapFeatureFlagsEnvToState', () => {
expect(mapFeatureFlagsEnvToState(config).enableStripOperationToolset).toBe(false);
});
});
+
+ describe('agent_inline_first_step', () => {
+ it('is off by default', () => {
+ expect(DEFAULT_FEATURE_FLAGS.agent_inline_first_step).toBe(false);
+ expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableInlineFirstStep).toBe(
+ false,
+ );
+ });
+
+ it('maps a user allowlist to the listed users only', () => {
+ const config = FeatureFlagsSchema.parse({ agent_inline_first_step: ['user-1'] });
+
+ expect(mapFeatureFlagsEnvToState(config, 'user-1').enableInlineFirstStep).toBe(true);
+ expect(mapFeatureFlagsEnvToState(config, 'user-2').enableInlineFirstStep).toBe(false);
+ });
+ });
});
diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.ts
index bb887c4b6cb..a2baa0dbea7 100644
--- a/packages/app-config/src/featureFlags/schema.ts
+++ b/packages/app-config/src/featureFlags/schema.ts
@@ -65,6 +65,15 @@ export const FeatureFlagsSchema = z.object({
*/
agent_deferred_hetero_dispatch: FeatureFlagValue.optional(),
+ /**
+ * Rollout gate for running step 0 of a deferred-init chat send inside the
+ * `execAgent` invocation, after its response is sent, instead of waiting for
+ * the queue to deliver it. The queued delivery is still published, later, as
+ * the fallback. Off: step 0 is delivered by the queue. Only the server reads
+ * it. Array values are user ids.
+ */
+ agent_inline_first_step: FeatureFlagValue.optional(),
+
/**
* Keep the immutable per-operation tool set out of the agent state blob that
* is rewritten at every step; it is written once to its own Redis key and
@@ -220,6 +229,7 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
agent_llm_relay: false,
agent_deferred_init: false,
agent_deferred_hetero_dispatch: false,
+ agent_inline_first_step: false,
agent_runtime_strip_operation_toolset: false,
// Off until an admin publishes a user allowlist or flips it to true.
@@ -288,6 +298,11 @@ export const mapFeatureFlagsEnvToState = (
userId,
'agent_deferred_hetero_dispatch',
),
+ enableInlineFirstStep: evaluateFeatureFlag(
+ config.agent_inline_first_step,
+ userId,
+ 'agent_inline_first_step',
+ ),
enableStripOperationToolset: evaluateFeatureFlag(
config.agent_runtime_strip_operation_toolset,
userId,
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index a1b0db5e2cf..f30f7e0429a 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -77,6 +77,11 @@ export type IFeatureFlagsState = {
* before the device dispatch completes (`agent_deferred_hetero_dispatch`).
*/
enableDeferredHeteroDispatch: boolean | undefined;
+ /**
+ * Step 0 of a deferred-init chat send runs in the `execAgent` invocation after
+ * its response, with the queued delivery kept as a fallback (`agent_inline_first_step`).
+ */
+ enableInlineFirstStep: boolean | undefined;
/**
* Creating managed cloud devices (`managed_cloud_device`). Off by default: the "Create in
* cloud" entry is hidden and the creation APIs answer FORBIDDEN. Existing managed devices keep