π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β‘οΈ perf(agent): run consecutive agent steps in one invocation (#19470)
Arvin Xu7712888372d8
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.tsindex 51e1b07edf7..7d95919074d 100644--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts@@ -318,6 +318,45 @@ export class AgentRuntimeCoordinator {return this.stateManager.cleanupExpiredOperations();}+ /**+ * Park the envelope for the step an inline loop is about to run. This stands in+ * for the queue message that the loop chose not to publish, so a redelivery+ * that arrives after the loop died resumes from the step it actually reached+ * instead of being dismissed as a stale duplicate.+ */+ async saveInlineResume<T>(operationId: string, envelope: T): Promise<boolean> {+ return this.stateManager.saveInlineResume(operationId, JSON.stringify(envelope));+ }++ /**+ * Read a parked inline envelope. Returns null when there is none.+ *+ * A read failure propagates, so the delivery is retried rather than treated as+ * "no envelope" β see `loadInlineResume` on the state manager. A value that no+ * longer parses is different: retrying cannot fix it, so it is reported and+ * treated as absent instead of looping the delivery into the DLQ.+ */+ async loadInlineResume<T>(operationId: string): Promise<null | T> {+ const serialized = await this.stateManager.loadInlineResume(operationId);+ if (!serialized) return null;++ try {+ return JSON.parse(serialized) as T;+ } catch (error) {+ console.error(`Unparseable inline resume envelope for ${operationId}:`, error);+ return null;+ }+ }++ /**+ * Drop a parked inline envelope once the queue owns the next step again.+ * Scoped to the lock owner, so a worker that lost the race cannot delete the+ * envelope of the worker that is still running.+ */+ async clearInlineResume(operationId: string, ownerId: string): Promise<void> {+ return this.stateManager.clearInlineResume(operationId, ownerId);+ }+/*** 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.tsindex a7dc2ef9b80..b0e7976a629 100644--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts@@ -13,8 +13,36 @@ const log = debug('lobe-server:agent-runtime:agent-state-manager');const REFRESH_OWNED_LOCK_SCRIPT ="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('expire', KEYS[1], ARGV[2]) else return 0 end";+/**+ * Drop the inline envelope only while this worker still owns the operation lock.+ *+ * An unconditional DEL is unsafe: a redelivery can read envelope k, stall while+ * the active worker finishes k and parks k+1, then lose the lock race and be+ * told its step is stale. Clearing there would delete a live worker's newer+ * recovery pointer. Ownership of the lock is exactly the right predicate β+ * whoever holds it is the worker whose envelope this is.+ *+ * KEYS[1] = operation lock, KEYS[2] = inline resume envelope, ARGV[1] = owner.+ */+const CLEAR_OWNED_INLINE_RESUME_SCRIPT =+ "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[2]) else return 0 end";const RELEASE_OWNED_LOCK_SCRIPT ="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";+/**+ * Claim the lock, or re-enter it when this exact owner already holds it.+ *+ * Re-entry exists for the inline step loop, which runs several steps under one+ * lock. Owner ids carry a random UUID (see `createStepLockOwner`), so only the+ * invocation that took the lock can present its owner id β a redelivery from+ * the queue always mints a different one and still loses the race.+ */+const CLAIM_OR_REENTER_LOCK_SCRIPT = `+if redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2], 'NX') then return 1 end+if redis.call('get', KEYS[1]) == ARGV[1] then+ redis.call('expire', KEYS[1], ARGV[2])+ return 1+end+return 0`;export interface StepResult {events?: AgentEvent[];@@ -71,6 +99,7 @@ export class AgentStateManager {private readonly STEPS_PREFIX = 'agent_runtime_steps';private readonly METADATA_PREFIX = 'agent_runtime_meta';private readonly INTERRUPT_PREFIX = 'agent_runtime_interrupt';+ private readonly INLINE_RESUME_PREFIX = 'agent_runtime_inline_resume';private readonly DEFAULT_TTL = 2 * 3600; // 2hconstructor() {@@ -390,6 +419,7 @@ export class AgentStateManager {`${this.STEPS_PREFIX}:${operationId}`,`${this.METADATA_PREFIX}:${operationId}`,`${this.INTERRUPT_PREFIX}:${operationId}`,+ `${this.INLINE_RESUME_PREFIX}:${operationId}`,];try {@@ -500,6 +530,60 @@ export class AgentStateManager {}}+ /**+ * The inline step loop's envelope for the step it is about to run. This is the+ * queue message that would otherwise be in flight β parked here instead, so a+ * redelivery arriving after the loop died can pick the operation back up from+ * where it actually stopped rather than from the delivered (older) step index.+ */+ async saveInlineResume(operationId: string, serialized: string): Promise<boolean> {+ try {+ await this.redis.setex(+ `${this.INLINE_RESUME_PREFIX}:${operationId}`,+ this.DEFAULT_TTL,+ serialized,+ );+ return true;+ } catch (error) {+ // Reported, never swallowed: the caller must fall back to the queue, or+ // it would run the next step with no recovery path behind it at all.+ console.error('Failed to save inline resume pointer:', error);+ return false;+ }+ }++ /**+ * Deliberately not wrapped in a try/catch. "No envelope" and "could not read+ * the envelope" have opposite consequences: the first means run the delivered+ * step, the second means an operation may be mid-loop with nothing queued+ * behind it. Swallowing the error would ACK that delivery as stale and strand+ * the run, so the failure propagates and the queue retries instead.+ */+ async loadInlineResume(operationId: string): Promise<null | string> {+ return this.redis.get(`${this.INLINE_RESUME_PREFIX}:${operationId}`);+ }++ /**+ * Owner-scoped, and best-effort on failure: a stale envelope is harmless. It+ * only ever resumes a step whose index is ahead of the delivered one, and the+ * next step to park overwrites it β worst case it expires with the+ * operation's TTL. Deleting someone else's envelope is not harmless, hence+ * the ownership check.+ */+ async clearInlineResume(operationId: string, ownerId: string): Promise<void> {+ try {+ await this.redis.eval(+ CLEAR_OWNED_INLINE_RESUME_SCRIPT,+ 2,+ this.executionLockKey(operationId),+ `${this.INLINE_RESUME_PREFIX}:${operationId}`,+ ownerId,+ );+ } catch (error) {+ console.error('Failed to clear inline resume pointer:', error);+ }+ }+private executionLockKey(operationId: string): string {return `agent_runtime_operation_lock:${operationId}`;}@@ -511,15 +595,15 @@ export class AgentStateManager {ownerId: string = Date.now().toString(),): Promise<boolean> {try {- const result = await this.redis.set(+ const result = await this.redis.eval(+ CLAIM_OR_REENTER_LOCK_SCRIPT,+ 1,this.executionLockKey(operationId),ownerId,- 'EX',- ttlSeconds,- 'NX',+ ttlSeconds.toString(),);- return result === 'OK';+ return result === 1;} catch (error) {// Fail-open: on Redis error, allow execution to proceedconsole.error('Failed to acquire step lock:', error);diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.tsindex e437dbb74f4..f16571992af 100644--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts@@ -15,6 +15,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {private steps: Map<string, any[]> = new Map();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 interrupted: Set<string> = new Set();private executionLockKey(operationId: string): string {@@ -147,6 +148,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {this.steps.delete(operationId);this.metadata.delete(operationId);this.interrupted.delete(operationId);+ this.inlineResumes.delete(operationId);log('Deleted operation %s', operationId);}@@ -218,6 +220,25 @@ export class InMemoryAgentStateManager implements IAgentStateManager {return stats;}+ async saveInlineResume(operationId: string, serialized: string): Promise<boolean> {+ this.inlineResumes.set(operationId, serialized);+ return true;+ }++ async loadInlineResume(operationId: string): Promise<null | string> {+ return this.inlineResumes.get(operationId) ?? null;+ }++ async clearInlineResume(operationId: string, ownerId: string): Promise<void> {+ // Mirrors CLEAR_OWNED_INLINE_RESUME_SCRIPT: only the current lock owner may+ // drop the envelope, so a worker that lost the race cannot delete a live+ // worker's recovery pointer.+ const lock = this.stepLocks.get(this.executionLockKey(operationId));+ if (lock?.ownerId !== ownerId) return;++ this.inlineResumes.delete(operationId);+ }+async tryClaimStep(operationId: string,_stepIndex: number,@@ -228,7 +249,10 @@ export class InMemoryAgentStateManager implements IAgentStateManager {const now = Date.now();const existing = this.stepLocks.get(key);- if (existing && existing.expiresAt > now) {+ // Re-entrant for the owner that already holds it, so an inline step loop can+ // run several steps without dropping the lock between them. Mirrors+ // CLAIM_OR_REENTER_LOCK_SCRIPT in the Redis-backed manager.+ if (existing && existing.expiresAt > now && existing.ownerId !== ownerId) {return false;}diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.tsindex 970759cda2d..950acfba285 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts@@ -186,17 +186,35 @@ describe('AgentStateManager', () => {describe('step execution lock', () => {it('claims an operation-scoped lock with the provided owner token', async () => {- redisMock.set.mockResolvedValue('OK');+ redisMock.eval.mockResolvedValue(1);await expect(stateManager.tryClaimStep('op-lock', 3, 120, 'owner-1')).resolves.toBe(true);- expect(redisMock.set).toHaveBeenCalledWith(- 'agent_runtime_operation_lock:op-lock',- 'owner-1',- 'EX',- 120,- 'NX',- );+ const [script, keyCount, key, owner, ttl] = redisMock.eval.mock.calls[0];+ expect(script).toContain("'NX'");+ expect(keyCount).toBe(1);+ expect(key).toBe('agent_runtime_operation_lock:op-lock');+ expect(owner).toBe('owner-1');+ expect(ttl).toBe('120');+ });++ it('re-enters a lock the same owner already holds', async () => {+ // The inline step loop runs several steps under one lock. Re-entry keeps+ // the lock unbroken across step boundaries; owner tokens carry a random+ // UUID, so only the invocation that took the lock can present its token.+ redisMock.eval.mockResolvedValue(1);++ await expect(stateManager.tryClaimStep('op-lock', 4, 120, 'owner-1')).resolves.toBe(true);++ const script = redisMock.eval.mock.calls[0][0] as string;+ expect(script).toContain("redis.call('get', KEYS[1]) == ARGV[1]");+ expect(script).toContain("redis.call('expire', KEYS[1], ARGV[2])");+ });++ it('refuses a lock held by a different owner', async () => {+ redisMock.eval.mockResolvedValue(0);++ await expect(stateManager.tryClaimStep('op-lock', 5, 120, 'owner-2')).resolves.toBe(false);});it('refreshes only the lock owned by the caller', async () => {@@ -253,7 +271,64 @@ describe('AgentStateManager', () => {'agent_runtime_steps:op-del','agent_runtime_meta:op-del','agent_runtime_interrupt:op-del',+ 'agent_runtime_inline_resume:op-del',+ );+ });+ });++ describe('inline resume envelope', () => {+ it('parks the envelope under the operation TTL', async () => {+ await expect(stateManager.saveInlineResume('op-resume', '{"stepIndex":4}')).resolves.toBe(+ true,);++ expect(redisMock.setex).toHaveBeenCalledWith(+ 'agent_runtime_inline_resume:op-resume',+ 2 * 3600,+ '{"stepIndex":4}',+ );+ });++ it('reads the envelope', async () => {+ redisMock.get.mockResolvedValue('{"stepIndex":4}');+ await expect(stateManager.loadInlineResume('op-resume')).resolves.toBe('{"stepIndex":4}');+ });++ it('clears the envelope only for the current lock owner', async () => {+ // An unconditional DEL lets a worker that lost the lock race delete the+ // newer envelope a live worker just parked, stranding it if it then dies.+ redisMock.eval.mockResolvedValue(1);++ await stateManager.clearInlineResume('op-resume', 'owner-1');++ const [script, keyCount, lockKey, resumeKey, owner] = redisMock.eval.mock.calls[0];+ expect(script).toContain("redis.call('get', KEYS[1]) == ARGV[1]");+ expect(script).toContain("redis.call('del', KEYS[2])");+ expect(keyCount).toBe(2);+ expect(lockKey).toBe('agent_runtime_operation_lock:op-resume');+ expect(resumeKey).toBe('agent_runtime_inline_resume:op-resume');+ expect(owner).toBe('owner-1');+ });++ it('reports a failed park so the caller can fall back to the queue', async () => {+ // Silently swallowing this would inline the next step with no envelope and+ // no queue message behind it β the exact stranding the envelope prevents.+ redisMock.setex.mockRejectedValueOnce(new Error('redis down'));+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(function () {});++ await expect(stateManager.saveInlineResume('op-resume', '{"stepIndex":4}')).resolves.toBe(+ false,+ );+ errorSpy.mockRestore();+ });++ it('surfaces a read failure instead of reporting no envelope', async () => {+ // "No envelope" means run the delivered step; "could not read the+ // envelope" may mean an operation is mid-loop with nothing queued behind+ // it. Collapsing the two would ACK that delivery as stale and strand it.+ redisMock.get.mockRejectedValue(new Error('redis down'));++ await expect(stateManager.loadInlineResume('op-resume')).rejects.toThrow('redis down');});});});diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.tsindex 86a88c0c1a0..dfc39a1736a 100644--- a/apps/server/src/modules/AgentRuntime/types.ts+++ b/apps/server/src/modules/AgentRuntime/types.ts@@ -29,6 +29,9 @@ export interface IAgentStateManager {*/cleanupExpiredOperations: () => Promise<number>;+ /** Drop the inline step loop's parked envelope, if this owner still holds the lock. */+ clearInlineResume: (operationId: string, ownerId: string) => Promise<void>;+/*** Create new operation metadata*/@@ -97,6 +100,9 @@ export interface IAgentStateManager {*/loadAgentState: (operationId: string) => Promise<AgentState | null>;+ /** Read the inline step loop's parked envelope, if any. */+ loadInlineResume: (operationId: string) => Promise<null | string>;+/*** Set the interrupt sentinel for the operation, alongside the* authoritative `status: 'interrupted'` in the persisted state.@@ -123,6 +129,12 @@ export interface IAgentStateManager {*/saveAgentState: (operationId: string, state: AgentState) => Promise<void>;+ /**+ * Park the envelope for the step an inline loop is about to run, so a+ * redelivery can resume from it if the loop dies mid-run.+ */+ saveInlineResume: (operationId: string, serialized: string) => Promise<boolean>;+/*** Save step execution result*/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.tsindex 02d4354e4cf..b3eee1e2d41 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@@ -6,13 +6,19 @@ import { AiAgentService } from '@/server/services/aiAgent';import { runStep, runStepHealth } from '../runStep';const mockGetOperationMetadata = vi.fn();+const mockLoadInlineResume = vi.fn();+const mockClearInlineResume = vi.fn();const mockExecuteStep = vi.fn();+const mockScheduleContinuation = vi.fn();+const mockReleaseOperationLock = vi.fn();const mockGetServerDB = vi.hoisted(() => vi.fn());vi.mock('@/server/modules/AgentRuntime', () => ({AgentRuntimeCoordinator: vi.fn().mockImplementation(function () {return {+ clearInlineResume: mockClearInlineResume,getOperationMetadata: mockGetOperationMetadata,+ loadInlineResume: mockLoadInlineResume,};}),}));@@ -20,7 +26,10 @@ vi.mock('@/server/modules/AgentRuntime', () => ({vi.mock('@/server/services/aiAgent', () => ({AiAgentService: vi.fn().mockImplementation(function () {return {+ createOperationLockOwner: (operationId: string) => `${operationId}:owner`,executeStep: mockExecuteStep,+ releaseOperationLock: mockReleaseOperationLock,+ scheduleContinuation: mockScheduleContinuation,};}),}));@@ -29,6 +38,11 @@ vi.mock('@/database/core/db-adaptor', () => ({getServerDB: mockGetServerDB,}));+const mockInlineStepsEnabled = vi.fn();+vi.mock('@/server/services/agentRuntime/inlineStepsGate', () => ({+ isInlineAgentStepsEnabledForUser: (userId: string) => mockInlineStepsEnabled(userId),+}));+function buildOperationDiagnosticDB(row?: any) {return {select: vi.fn(function () {@@ -81,7 +95,14 @@ const validBody = {describe('runStep handler', () => {beforeEach(() => {mockGetOperationMetadata.mockReset();+ mockInlineStepsEnabled.mockReset();+ mockInlineStepsEnabled.mockResolvedValue(true);+ mockLoadInlineResume.mockReset();+ mockLoadInlineResume.mockResolvedValue(null);+ mockClearInlineResume.mockReset();mockExecuteStep.mockReset();+ mockScheduleContinuation.mockReset();+ mockReleaseOperationLock.mockReset();mockGetServerDB.mockResolvedValue({} as any);});@@ -391,3 +412,385 @@ describe('runStepHealth handler', () => {});});});++describe('runStep inline step loop', () => {+ const metadata = { userId: 'user-1', workspaceId: 'ws-1' };+ const doneState = { cost: { total: 0 }, status: 'done', stepCount: 4 };++ const continuationFor = (stepIndex: number) => ({+ context: { phase: 'llm_result', step: stepIndex },+ delay: 50,+ operationId: 'op-1',+ priority: 'normal' as const,+ stepIndex,+ });++ beforeEach(() => {+ // This is a separate top-level describe, so it does not inherit the reset+ // above β without these, one test's stub leaks into the next.+ mockGetOperationMetadata.mockReset();+ mockExecuteStep.mockReset();+ mockScheduleContinuation.mockReset();+ mockReleaseOperationLock.mockReset();+ mockClearInlineResume.mockReset();+ mockLoadInlineResume.mockReset();+ mockLoadInlineResume.mockResolvedValue(null);+ mockInlineStepsEnabled.mockReset();+ mockInlineStepsEnabled.mockResolvedValue(true);+ mockGetServerDB.mockResolvedValue({} as any);+ mockGetOperationMetadata.mockResolvedValue(metadata);+ });++ it('runs consecutive steps in one invocation instead of re-queueing each one', async () => {+ // The whole point of the loop: three steps, zero queue round-trips.+ mockExecuteStep+ .mockResolvedValueOnce({+ continuation: continuationFor(3),+ nextStepScheduled: false,+ state: { status: 'running', stepCount: 3 },+ success: true,+ })+ .mockResolvedValueOnce({+ continuation: continuationFor(4),+ nextStepScheduled: false,+ state: { status: 'running', stepCount: 4 },+ success: true,+ })+ .mockResolvedValueOnce({+ nextStepScheduled: false,+ state: doneState,+ success: true,+ });++ const { ctx, getCaptures } = buildContext({ body: validBody });+ const res = await runStep(ctx);++ expect(res.status).toBe(200);+ expect(mockExecuteStep).toHaveBeenCalledTimes(3);+ expect(mockScheduleContinuation).not.toHaveBeenCalled();+ expect(getCaptures()[0].body).toMatchObject({+ completed: true,+ inlinedSteps: 2,+ nextStepScheduled: false,+ // The response reports the last step actually executed, not the delivered one.+ stepIndex: 4,+ });+ });++ it('carries the delivery payload on the first step only', async () => {+ // Human input / approvals / retry counters describe THIS delivery. Replaying+ // them on an inlined step would re-apply an approval that already ran.+ mockExecuteStep+ .mockResolvedValueOnce({+ continuation: continuationFor(3),+ nextStepScheduled: false,+ state: { status: 'running', stepCount: 3 },+ success: true,+ })+ .mockResolvedValueOnce({ nextStepScheduled: false, state: doneState, success: true });++ const { ctx } = buildContext({+ body: { ...validBody, approvedToolCall: { id: 'call-1' }, humanInput: 'yes' },+ retried: '2',+ });+ await runStep(ctx);++ expect(mockExecuteStep.mock.calls[0][0]).toMatchObject({+ approvedToolCall: { id: 'call-1' },+ externalRetryCount: 2,+ humanInput: 'yes',+ stepIndex: 2,+ });+ const second = mockExecuteStep.mock.calls[1][0];+ expect(second.approvedToolCall).toBeUndefined();+ expect(second.humanInput).toBeUndefined();+ expect(second.externalRetryCount).toBeUndefined();+ expect(second.stepIndex).toBe(3);+ });++ it('holds one lock owner across every inlined step and releases it once', async () => {+ mockExecuteStep+ .mockResolvedValueOnce({+ continuation: continuationFor(3),+ nextStepScheduled: false,+ state: { status: 'running', stepCount: 3 },+ success: true,+ })+ .mockResolvedValueOnce({ nextStepScheduled: false, state: doneState, success: true });++ const { ctx } = buildContext({ body: validBody });+ await runStep(ctx);++ for (const [params] of mockExecuteStep.mock.calls) {+ expect(params).toMatchObject({ retainStepLock: true, stepLockOwner: 'op-1:owner' });+ }+ expect(mockReleaseOperationLock).toHaveBeenCalledTimes(1);+ expect(mockReleaseOperationLock).toHaveBeenCalledWith('op-1', 'op-1:owner');+ });++ it('hands the pending step back to the queue once the deadline passes', async () => {+ let clock = Date.now();+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => clock);+ const pending = continuationFor(3);++ mockExecuteStep.mockImplementation(async () => {+ // Burn the whole inline budget inside the first step.+ clock += 600_000;+ return {+ continuation: pending,+ nextStepScheduled: false,+ state: { status: 'running', stepCount: 3 },+ success: true,+ };+ });++ const { ctx, getCaptures } = buildContext({ body: validBody });+ const res = await runStep(ctx);++ expect(res.status).toBe(200);+ expect(mockExecuteStep).toHaveBeenCalledTimes(1);+ expect(mockScheduleContinuation).toHaveBeenCalledWith(pending);+ expect(getCaptures()[0].body).toMatchObject({ nextStepScheduled: true, nextStepIndex: 3 });+ expect(mockReleaseOperationLock).toHaveBeenCalledWith('op-1', 'op-1:owner');+ nowSpy.mockRestore();+ });++ it('releases the lock when a step throws', async () => {+ // Without this the operation stays locked for the full TTL and every+ // redelivery bounces off it.+ mockExecuteStep.mockRejectedValue(new Error('boom'));+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(function () {});++ const { ctx } = buildContext({ body: validBody });+ const res = await runStep(ctx);++ expect(res.status).toBe(500);+ expect(mockReleaseOperationLock).toHaveBeenCalledWith('op-1', 'op-1:owner');+ errorSpy.mockRestore();+ });++ it('resumes from a parked envelope left behind by a dead inline loop', async () => {+ // Without this the delivered (older) step index hits the stepCount > stepIndex+ // stale-delivery guard, gets ACKed, and the operation stalls forever with+ // nothing queued behind it β the inline loop never published a message.+ const parked = continuationFor(7);+ mockLoadInlineResume.mockResolvedValue(parked);+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: false,+ state: doneState,+ success: true,+ });++ const { ctx, getCaptures } = buildContext({ body: validBody });+ await runStep(ctx);++ const params = mockExecuteStep.mock.calls[0][0];+ expect(params.stepIndex).toBe(7);+ expect(params.context).toEqual(parked.context);+ expect(getCaptures()[0].body).toMatchObject({ stepIndex: 7 });+ });++ it('keeps the delivery retry count when resuming a parked step', async () => {+ // A step that parked for approval but failed to persist its Review is only+ // replayed while `externalRetryCount > 0`. Dropping it on the resume path+ // lets the stale-delivery guard ACK the step, and the approval never+ // becomes available.+ mockLoadInlineResume.mockResolvedValue(continuationFor(7));+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: false,+ state: doneState,+ success: true,+ });++ const { ctx } = buildContext({ body: validBody, retried: '2' });+ await runStep(ctx);++ expect(mockExecuteStep.mock.calls[0][0]).toMatchObject({+ externalRetryCount: 2,+ stepIndex: 7,+ });+ });++ it('fails the delivery when the parked envelope cannot be read', async () => {+ // Treating an unreadable envelope as an absent one would run the delivered+ // (older) step, get ACKed as stale, and strand the operation. A 500 lets the+ // queue retry instead.+ mockLoadInlineResume.mockRejectedValue(new Error('redis down'));+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(function () {});++ const { ctx } = buildContext({ body: validBody });+ const res = await runStep(ctx);++ expect(res.status).toBe(500);+ expect(mockExecuteStep).not.toHaveBeenCalled();+ errorSpy.mockRestore();+ });++ it('never redirects a purpose-carrying delivery to a parked envelope', async () => {+ // The group-member timeout watchdog is scheduled on the member operation at+ // stepIndex 0, so any envelope would be "ahead" of it. Redirecting it would+ // drop the watchdog payload AND delete the running loop's recovery pointer.+ // Same reasoning for approvals, resumes and barrier probes.+ const purposeful = [+ { approvedToolCall: { id: 'call-1' } },+ { finishAfterAsyncTool: true },+ { groupMemberTimeout: { memberOperationId: 'op-member' } },+ { humanInput: 'yes' },+ { rejectAndContinue: true },+ { rejectionReason: 'nope' },+ { resumeAsyncTool: true },+ { toolMessageId: 'msg-1' },+ { verifyAsyncToolBarrier: true },+ ];+ mockLoadInlineResume.mockResolvedValue(continuationFor(7));+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: false,+ state: doneState,+ success: true,+ });++ for (const payload of purposeful) {+ mockExecuteStep.mockClear();+ mockClearInlineResume.mockClear();++ const { ctx } = buildContext({ body: { ...validBody, ...payload } });+ await runStep(ctx);++ expect(mockExecuteStep.mock.calls[0][0]).toMatchObject({ stepIndex: 2, ...payload });+ // The envelope belongs to whoever is actually looping; this delivery must+ // not clear it on the way past.+ expect(mockClearInlineResume).not.toHaveBeenCalled();+ }+ });++ it('scopes the envelope clear to this invocation lock owner', async () => {+ // A delivery can read envelope k, stall while the live worker finishes k and+ // parks k+1, then be told its step is stale. Clearing unconditionally there+ // would delete the live worker's newer recovery pointer.+ mockLoadInlineResume.mockResolvedValue(continuationFor(7));+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: false,+ state: doneState,+ success: true,+ });++ const { ctx } = buildContext({ body: validBody });+ await runStep(ctx);++ expect(mockClearInlineResume).toHaveBeenCalledWith('op-1', 'op-1:owner');+ });++ it('ignores a parked envelope that is not ahead of the delivered step', async () => {+ // After a deadline hand-off the queued message carries the same index the+ // envelope named. That delivery is authoritative, payload and all.+ mockLoadInlineResume.mockResolvedValue(continuationFor(2));+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: false,+ state: doneState,+ success: true,+ });++ const { ctx } = buildContext({ body: { ...validBody, humanInput: 'yes' } });+ await runStep(ctx);++ expect(mockExecuteStep.mock.calls[0][0]).toMatchObject({+ humanInput: 'yes',+ stepIndex: 2,+ });+ });++ it('drops the parked envelope when the pending step goes back to the queue', async () => {+ // Otherwise the envelope and the queued message both point at the same step,+ // and a late redelivery could run it a second time.+ let clock = Date.now();+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => clock);+ mockExecuteStep.mockImplementation(async () => {+ clock += 600_000;+ return {+ continuation: continuationFor(3),+ nextStepScheduled: false,+ state: { status: 'running', stepCount: 3 },+ success: true,+ };+ });++ const { ctx } = buildContext({ body: validBody });+ await runStep(ctx);++ expect(mockScheduleContinuation).toHaveBeenCalledTimes(1);+ expect(mockClearInlineResume).toHaveBeenCalledWith('op-1', 'op-1:owner');+ nowSpy.mockRestore();+ });++ it('runs one step per delivery when the rollout flag is off', async () => {+ mockInlineStepsEnabled.mockResolvedValue(false);+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: true,+ state: { status: 'running', stepCount: 3 },+ success: true,+ });++ const { ctx, getCaptures } = buildContext({ body: validBody });+ await runStep(ctx);++ expect(mockInlineStepsEnabled).toHaveBeenCalledWith('user-1');+ expect(mockExecuteStep).toHaveBeenCalledTimes(1);+ expect(mockExecuteStep.mock.calls[0][0]).toMatchObject({ inlineContinuation: false });+ expect(getCaptures()[0].body).toMatchObject({ inlinedSteps: 0, nextStepScheduled: true });+ });++ it('still honours a parked envelope after the flag is switched off', async () => {+ // Operations that were mid-loop when the flag flipped have an envelope and+ // nothing queued behind them. Ignoring it would strand exactly the runs the+ // rollback was meant to protect.+ mockInlineStepsEnabled.mockResolvedValue(false);+ mockLoadInlineResume.mockResolvedValue(continuationFor(7));+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: true,+ state: { status: 'running', stepCount: 8 },+ success: true,+ });++ const { ctx } = buildContext({ body: validBody });+ await runStep(ctx);++ expect(mockExecuteStep.mock.calls[0][0]).toMatchObject({+ inlineContinuation: false,+ stepIndex: 7,+ });+ // The queue owns the next step again, so the envelope must not linger.+ expect(mockClearInlineResume).toHaveBeenCalledWith('op-1', 'op-1:owner');+ });++ it('leaves Redis alone when nothing was ever parked', async () => {+ mockInlineStepsEnabled.mockResolvedValue(false);+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: true,+ state: { status: 'running', stepCount: 3 },+ success: true,+ });++ const { ctx } = buildContext({ body: validBody });+ await runStep(ctx);++ expect(mockClearInlineResume).not.toHaveBeenCalled();+ });++ it('stops the loop and reports success when another worker takes the lock mid-run', async () => {+ mockExecuteStep+ .mockResolvedValueOnce({+ continuation: continuationFor(3),+ nextStepScheduled: false,+ state: { status: 'running', stepCount: 3 },+ success: true,+ })+ .mockResolvedValueOnce({ locked: true, nextStepScheduled: false, state: {}, success: false });++ const { ctx, getCaptures } = buildContext({ body: validBody });+ const res = await runStep(ctx);++ expect(res.status).toBe(200);+ expect(mockScheduleContinuation).not.toHaveBeenCalled();+ expect(getCaptures()[0].body).toMatchObject({ inlinedSteps: 1 });+ });+});diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.tsindex d5cb12ae672..aaf1967f3e3 100644--- a/apps/server/src/router-hono/agent/handlers/runStep.ts+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts@@ -5,10 +5,30 @@ import type { Context } from 'hono';import { getServerDB } from '@/database/core/db-adaptor';import { agentOperations } from '@/database/schemas/agentOperations';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';+import type { AgentExecutionResult, AgentStepContinuation } from '@/server/services/agentRuntime';+import { isInlineAgentStepsEnabledForUser } from '@/server/services/agentRuntime/inlineStepsGate';import { AiAgentService } from '@/server/services/aiAgent';const log = debug('lobe-server:agent:run-step');+/**+ * Latest point in an invocation at which a new step may START, in ms.+ *+ * Every step boundary used to cost a full queue round-trip β measured at ~2.9s+ * p50 across production traces, which is 13% of all agent-run wall time and+ * more than a quarter of it for multi-step operations. Running consecutive+ * steps inside one invocation removes that cost; this deadline is what keeps+ * the invocation inside the platform's function timeout.+ *+ * It must stay comfortably below the route's `maxDuration`, because a step that+ * starts just under the deadline still runs to completion β production LLM+ * steps are ~42s at p90 and ~125s at p99. The 450s default leaves ~150s of+ * headroom under a 600s `maxDuration`, which covers p99. Raise it only+ * alongside `maxDuration`. Once past the deadline the pending step goes back to+ * the queue and a fresh invocation picks it up.+ */+const INLINE_STEP_START_DEADLINE_MS = Number(process.env.AGENT_INLINE_STEP_DEADLINE_MS ?? 450_000);+const toIsoString = (value: Date | string | null | undefined): null | string => {if (!value) return null;if (value instanceof Date) return value.toISOString();@@ -140,27 +160,171 @@ export async function runStep(c: Context): Promise<Response> {workspaceId: metadata.workspaceId,});- const result = await aiAgentService.executeStep({- approvedToolCall,- asyncToolVerifyAttempt,- context,- externalRetryCount,- humanInput,- finishAfterAsyncTool,- groupMemberTimeout,- lockRetryAttempt,- operationId,- rejectAndContinue,- rejectionReason,- resumeAsyncTool,- stepIndex,- toolMessageId,- verifyAsyncToolBarrier,- });+ // ===== 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.+ // Rollout switch, resolved once per invocation from RuntimeConfig (Redis,+ // cached ~5s per instance). Off means exactly one step per delivery, which+ // is what the worker has always done.+ const inlineEnabled = await isInlineAgentStepsEnabledForUser(metadata.userId);++ 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 &&+ !groupMemberTimeout;++ // Deliberately not gated on `inlineEnabled`: switching the flag off while+ // operations are mid-loop must not strand the ones that already have an+ // envelope parked and nothing queued behind them.+ // 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 {+ // 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: inlineEnabled,+ operationId,+ retainStepLock: true,+ stepIndex: resumeFrom.stepIndex,+ stepLockOwner,+ })+ : await aiAgentService.executeStep({+ approvedToolCall,+ asyncToolVerifyAttempt,+ context,+ externalRetryCount,+ finishAfterAsyncTool,+ groupMemberTimeout,+ humanInput,+ inlineContinuation: inlineEnabled,+ lockRetryAttempt,+ operationId,+ rejectAndContinue,+ rejectionReason,+ resumeAsyncTool,+ retainStepLock: true,+ stepIndex,+ stepLockOwner,+ toolMessageId,+ verifyAsyncToolBarrier,+ });+ pendingContinuation = result.continuation;+ touchedEnvelope ||= Boolean(pendingContinuation);++ while (pendingContinuation) {+ 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: inlineEnabled,+ 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);+ }// A non-stale lock conflict means another delivery is still executing this- // operation.- if (result.locked) {+ // operation. Once the inline loop has run steps of its own the delivery has+ // already done real work and the conflict just means another worker picked+ // up the rest, so report success instead of asking for a redelivery that the+ // stale-step guard would drop anyway.+ if (result.locked && inlinedSteps === 0) {// The runtime already re-queued this step on its own backoff, which can// outlast a step that holds the lock for minutes. ACK so QStash doesn't// retry on top of that and dead-letter the delivery once its (much@@ -192,14 +356,15 @@ export async function runStep(c: Context): Promise<Response> {completed: result.state.status === 'done',error: result.state.status === 'error' ? result.state.error : undefined,executionTime,- nextStepIndex: result.nextStepScheduled ? stepIndex + 1 : undefined,+ inlinedSteps,+ nextStepIndex: result.nextStepScheduled ? currentStepIndex + 1 : undefined,nextStepScheduled: result.nextStepScheduled,operationId,pendingApproval: result.state.pendingToolsCalling,pendingPrompt: result.state.pendingHumanPrompt,pendingSelect: result.state.pendingHumanSelect,status: result.state.status,- stepIndex,+ stepIndex: currentStepIndex,success: result.success,totalCost: result.state.cost?.total || 0,totalSteps: result.state.stepCount,@@ -207,7 +372,7 @@ export async function runStep(c: Context): Promise<Response> {};log(- `[${operationId}] Step ${stepIndex} completed (${executionTime}ms, status: ${result.state.status})`,+ `[${operationId}] Steps ${stepIndex}..${currentStepIndex} completed (${executionTime}ms, ${inlinedSteps} inlined, status: ${result.state.status})`,);return c.json(responseData);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 432536ba5b2..a14827c705c 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -93,6 +93,7 @@ import { buildStepPresentation, formatTokenCount } from './stepPresentation';import {type AgentExecutionParams,type AgentExecutionResult,+ type AgentStepContinuation,type ExecGroupMemberParams,type ExecGroupMemberResult,type GroupActionMemberBridgeParams,@@ -1274,6 +1275,9 @@ export class AgentRuntimeService {asyncToolVerifyAttempt,externalRetryCount = 0,lockRetryAttempt = 0,+ inlineContinuation = false,+ retainStepLock = false,+ stepLockOwner: providedStepLockOwner,} = params;// Group member timeout watchdog: enforce a member's deadline without claiming@@ -1344,7 +1348,7 @@ export class AgentRuntimeService {}// ===== Distributed lock: prevent duplicate execution from QStash retries =====- const stepLockOwner = createStepLockOwner(operationId, stepIndex);+ const stepLockOwner = providedStepLockOwner ?? createStepLockOwner(operationId, stepIndex);const claimed = await this.coordinator.tryClaimStep(operationId,stepIndex,@@ -2034,6 +2038,7 @@ export class AgentRuntimeService {}));let nextStepScheduled = false;+ let continuation: AgentStepContinuation | undefined;// Publish step complete eventawait this.streamManager.publishStreamEvent(operationId, {@@ -2197,31 +2202,62 @@ export class AgentRuntimeService {if (shouldContinue && stepResult.nextContext && this.queueService) {const nextStepIndex = stepIndex + 1;- const delay = this.calculateStepDelay(stepResult);- const priority = this.calculatePriority(stepResult);-- await this.queueService.scheduleMessage({+ const next: AgentStepContinuation = {context: stepResult.nextContext,- delay,- endpoint: `${this.baseURL}/run`,+ delay: this.calculateStepDelay(stepResult),operationId,- priority,- retryDelay:- typeof stepResult.newState.metadata?.queueRetryDelay === 'string'- ? stepResult.newState.metadata.queueRetryDelay- : undefined,+ priority: this.calculatePriority(stepResult),retries:typeof stepResult.newState.metadata?.queueRetries === 'number'? stepResult.newState.metadata.queueRetries: undefined,+ retryDelay:+ typeof stepResult.newState.metadata?.queueRetryDelay === 'string'+ ? stepResult.newState.metadata.queueRetryDelay+ : undefined,stepIndex: nextStepIndex,- });- nextStepScheduled = true;- logToolCallPc(operationId, stepIndex, 'post.next_step_scheduled', () => ({- nextStepIndex,- }));+ };++ // Park the envelope before handing it over. The caller is about to run+ // this step in-process with nothing queued behind it; if that+ // invocation dies mid-step, the only way back is for a redelivery to+ // find this envelope β the stale-delivery guard would otherwise ACK+ // the (now older) delivered step and strand the operation.+ //+ // Inlining is therefore conditional on the park succeeding. When it+ // doesn't, fall back to the ordinary queue round-trip: slower by a+ // step boundary, but it keeps the recovery path the queue provides.+ const parked = inlineContinuation+ ? await this.coordinator.saveInlineResume(operationId, next)+ : false;++ if (!parked && inlineContinuation) {+ log(+ '[%s][%d] Could not park the inline envelope; falling back to the queue',+ operationId,+ stepIndex,+ );+ }- log('[%s][%d] Scheduled next step %d', operationId, stepIndex, nextStepIndex);+ if (parked) {+ // Hand the next step back to the caller instead of paying a full+ // queue round-trip for it. The caller either runs it in this same+ // invocation or publishes it via `scheduleContinuation` when its+ // time budget runs out, so the step is never dropped.+ continuation = next;+ logToolCallPc(operationId, stepIndex, 'post.next_step_inlined', () => ({+ nextStepIndex,+ }));+ log('[%s][%d] Next step %d deferred to caller', operationId, stepIndex, nextStepIndex);+ } else {+ await this.queueService.scheduleMessage({ ...next, endpoint: `${this.baseURL}/run` });+ nextStepScheduled = true;+ logToolCallPc(operationId, stepIndex, 'post.next_step_scheduled', () => ({+ nextStepIndex,+ }));++ log('[%s][%d] Scheduled next step %d', operationId, stepIndex, nextStepIndex);+ }}// Record final agent-level usage on the invoke_agent span. Done on every@@ -2310,6 +2346,7 @@ export class AgentRuntimeService {}return {+ continuation,nextStepScheduled,state: stepResult.newState,stepResult,@@ -2451,10 +2488,51 @@ export class AgentRuntimeService {stepAbortPollStopped = true;if (stepAbortPoll) clearTimeout(stepAbortPoll);stopStepLockHeartbeat();- await this.coordinator.releaseStepLock(operationId, stepIndex, stepLockOwner);+ // The inline step loop keeps the lock across step boundaries β releasing+ // here would open a window for a stale redelivery to claim it mid-run.+ // Its caller releases once, in a `finally`, for the whole invocation.+ if (!retainStepLock) {+ await this.coordinator.releaseStepLock(operationId, stepIndex, stepLockOwner);+ }}}+ /**+ * Publish a continuation that `executeStep` handed back instead of queueing.+ * The inline step loop calls this when it runs out of invocation budget, so+ * the remaining steps resume in a fresh invocation.+ */+ async scheduleContinuation(continuation: AgentStepContinuation): Promise<void> {+ if (!this.queueService) {+ throw new Error(+ `Cannot schedule continuation for ${continuation.operationId}: no queue service`,+ );+ }++ await this.queueService.scheduleMessage({+ ...continuation,+ endpoint: `${this.baseURL}/run`,+ });++ log('[%s] Handed step %d back to the queue', continuation.operationId, continuation.stepIndex);+ }++ /**+ * Release a lock that was retained across an inline step loop. Owner-scoped,+ * so it is a no-op when this invocation never held the lock.+ */+ async releaseOperationLock(operationId: string, stepLockOwner: string): Promise<void> {+ await this.coordinator.releaseStepLock(operationId, 0, stepLockOwner);+ }++ /**+ * Mint a lock owner for an inline step loop. Unique per invocation, which is+ * what makes re-entering the same lock on the next step safe.+ */+ createOperationLockOwner(operationId: string): string {+ return createStepLockOwner(operationId, 0);+ }+/*** Get operation status*/diff --git a/apps/server/src/services/agentRuntime/inlineStepsGate.ts b/apps/server/src/services/agentRuntime/inlineStepsGate.tsnew file mode 100644index 00000000000..9bc77220b40--- /dev/null+++ b/apps/server/src/services/agentRuntime/inlineStepsGate.ts@@ -0,0 +1,28 @@+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';++/**+ * Resolves whether the queue worker may run consecutive steps of an operation+ * inside a single invocation.+ *+ * Use when:+ * - The QStash step worker is deciding how much of an operation to run+ * - Rollout eligibility must come from RuntimeConfig rather than a deploy+ *+ * Expects:+ * - `userId` is the owner of the operation being stepped+ *+ * Returns:+ * - `true` only when the inline-step flag is enabled for that user+ *+ * Fails closed: any error resolving the flag falls back to the one-step-per-+ * delivery behaviour the worker has always had.+ */+export const isInlineAgentStepsEnabledForUser = async (userId: string): Promise<boolean> => {+ try {+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);++ return featureFlags.enableInlineAgentSteps === true;+ } catch {+ return false;+ }+};diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 63542b14325..ad250ff3007 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -160,6 +160,13 @@ export interface AgentExecutionParams {*/groupMemberTimeout?: GroupMemberTimeoutParams;humanInput?: any;+ /**+ * Run the next step in this same invocation instead of publishing it to the+ * queue. When set and the operation wants to continue, `executeStep` returns+ * a `continuation` and leaves `nextStepScheduled` false β the caller decides+ * whether to loop or hand the continuation back to the queue.+ */+ inlineContinuation?: boolean;/*** 1-based attempt number carried by a re-delivery that a previous attempt* re-queued after losing the operation lock. Lets the bounded backoff stop@@ -181,7 +188,20 @@ export interface AgentExecutionParams {* via `tryResumeParentFromAsyncTool`.*/resumeAsyncTool?: boolean;+ /**+ * Keep the operation lock held after this step returns. Used by the inline+ * step loop so the lock spans the whole invocation rather than being dropped+ * and re-claimed at every boundary β the caller becomes responsible for+ * releasing it via `releaseOperationLock`.+ */+ retainStepLock?: boolean;stepIndex: number;+ /**+ * Reuse an existing lock owner instead of minting one per step. The inline+ * step loop passes a single owner for the whole invocation so every iteration+ * re-enters the same lock.+ */+ stepLockOwner?: string;/** ID of the pending tool message targeted by the intervention. */toolMessageId?: string;/**@@ -198,7 +218,30 @@ export interface AgentExecutionParams {verifyAsyncToolBarrier?: boolean;}+/**+ * A next step that was computed but deliberately not published, because the+ * caller asked for `inlineContinuation`. Carries everything `scheduleMessage`+ * needs so the caller can still hand it to the queue when it runs out of+ * invocation budget.+ */+export interface AgentStepContinuation {+ context: AgentRuntimeContext;+ delay: number;+ operationId: string;+ priority: 'high' | 'low' | 'normal';+ retries?: number;+ retryDelay?: string;+ stepIndex: number;+}+export interface AgentExecutionResult {+ /**+ * Present only when `inlineContinuation` was requested and the operation has+ * a next step ready to run now. Absent for every terminal outcome and for+ * every park (waiting_for_human, pending approval, async-tool wait), so an+ * inline loop can simply stop when it is missing.+ */+ continuation?: AgentStepContinuation;/*** When true, the step was already being executed by another instance (lock conflict).* Stale duplicates are handled before returning this; callers should keepdiff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 1c7c765f9be..9925be4a359 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -40,6 +40,7 @@ import type {AgentExecutionParams,AgentExecutionResult,AgentRuntimeServiceOptions,+ AgentStepContinuation,SubAgentBridgeParams,} from '@/server/services/agentRuntime';import { AgentRuntimeService } from '@/server/services/agentRuntime';@@ -302,6 +303,21 @@ export class AiAgentService {return this.agentRuntimeService.executeStep(params);}+ /** Mint a lock owner that spans a whole inline step loop. */+ createOperationLockOwner(operationId: string): string {+ return this.agentRuntimeService.createOperationLockOwner(operationId);+ }++ /** Publish a step that an inline loop deferred instead of running. */+ scheduleContinuation(continuation: AgentStepContinuation): Promise<void> {+ return this.agentRuntimeService.scheduleContinuation(continuation);+ }++ /** Release a lock retained across an inline step loop. */+ releaseOperationLock(operationId: string, stepLockOwner: string): Promise<void> {+ return this.agentRuntimeService.releaseOperationLock(operationId, stepLockOwner);+ }+/*** Run the sub-agent completion bridge against this service's runtime.*diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex fe7ed5bfcbd..645fba06792 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -44,6 +44,12 @@ export const FeatureFlagsSchema = z.object({agent_onboarding: FeatureFlagValue.optional(),dev_dock: FeatureFlagValue.optional(),dev_dock_workspaces: z.array(z.string()).optional(),+ /**+ * Rollout gate for the queue worker's inline step loop. Array values are user+ * IDs, so the loop can be switched on for a slice of traffic before everyone.+ * Off by default: the worker then runs one step per delivery, unchanged.+ */+ inline_agent_steps: FeatureFlagValue.optional(),// Cloud feature flag. Keep here until cloud owns a separate runtime flag domain.auth_captcha: FeatureFlagValue.optional(),cloud_promotion: FeatureFlagValue.optional(),@@ -105,6 +111,7 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {agent_self_iteration: isDev,agent_onboarding: isDev,dev_dock: isDev,+ inline_agent_steps: false,auth_captcha: true,cloud_promotion: false,onboarding_v2: isDev,@@ -152,6 +159,7 @@ export const mapFeatureFlagsEnvToState = (enableAgentSelfIteration: evaluateFeatureFlag(config.agent_self_iteration, userId),enableAgentOnboarding: evaluateFeatureFlag(config.agent_onboarding, userId),enableDevDock: evaluateFeatureFlag(config.dev_dock, userId),+ enableInlineAgentSteps: evaluateFeatureFlag(config.inline_agent_steps, userId),enableAuthCaptcha: evaluateFeatureFlag(config.auth_captcha, userId),enableOnboardingV2: evaluateFeatureFlag(config.onboarding_v2, userId),enableStorageOverage: evaluateFeatureFlag(config.storage_overage, userId),diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex f09cd58b712..21fee8bc574 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -28,6 +28,12 @@ export type IFeatureFlagsState = {enableAuthCaptcha: boolean | undefined;enableCheckUpdates: boolean | undefined;enableDevDock: boolean | undefined;+ /**+ * Lets the queue worker run consecutive agent steps inside one invocation+ * instead of paying a queue round-trip per step. Rollout switch only β with it+ * off the worker runs exactly one step per delivery, as it always has.+ */+ enableInlineAgentSteps: boolean | undefined;enableKnowledgeBase: boolean | undefined;enableOnboardingV2: boolean | undefined;enableRAGEval: boolean | undefined;