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.

✨ feat(agent): let a step run the init its operation was created without (#19798)

Arvin Xudafe514bad68
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.deferredInit.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.deferredInit.test.ts
new file mode 100644
index 00000000000..7829ff15f34
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.deferredInit.test.ts
@@ -0,0 +1,507 @@
+/**
+ * @vitest-environment node
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { hookDispatcher } from '../../hooks';
+import { type AgentExecutionParams } from '../../types';
+import { AgentRuntimeService } from '..';
+
+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)),
+);
+
+describe('AgentRuntimeService executeStep', () => {
+ const mockDb: any = { delete: vi.fn(), insert: vi.fn(), select: vi.fn(), update: vi.fn() };
+ const mockUserId = 'test-user-id';
+
+ const mockParams: AgentExecutionParams = {
+ operationId: 'test-operation-1',
+ stepIndex: 1,
+ context: {
+ phase: 'user_input',
+ payload: {
+ message: { content: 'test' },
+ sessionId: 'test-operation-1',
+ isFirstMessage: false,
+ },
+ session: {
+ sessionId: 'test-operation-1',
+ status: 'running',
+ stepCount: 1,
+ messageCount: 1,
+ },
+ },
+ };
+
+ const mockState = {
+ operationId: 'test-operation-1',
+ status: 'running',
+ stepCount: 1,
+ messages: [],
+ events: [],
+ lastModified: new Date().toISOString(),
+ };
+
+ const mockMetadata = {
+ userId: 'user-123',
+ agentConfig: { name: 'test-agent' },
+ modelRuntimeConfig: { model: 'gpt-4' },
+ createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
+ status: 'running',
+ totalCost: 0,
+ totalSteps: 1,
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ delete process.env.AGENT_RUNTIME_BASE_URL;
+ hookDispatcher.unregister('test-operation-1');
+ });
+
+ // A run created without its init (`state.request`) has to get discovery and the
+ // context assembly done here, before anything is published β€” the whole point
+ // of returning from the send path early.
+ describe('deferred init', () => {
+ const pendingState = () => ({
+ ...mockState,
+ messages: [],
+ origin: { agentId: 'agent-1', topicId: 'topic-1' },
+ // The turn's ask still on the state = the init has not run yet.
+ request: { approvedToolEntries: [], selectedToolIds: ['lobe-web-browsing'] },
+ stepCount: 0,
+ });
+
+ const buildService = (runDeferredInit: any) =>
+ new AgentRuntimeService(mockDb, mockUserId, { delegate: { runDeferredInit } });
+
+ const wireStep = (svc: AgentRuntimeService) => {
+ const step = vi.fn().mockImplementation(async (input) => ({
+ events: [],
+ newState: { ...input, stepCount: 2 },
+ nextContext: mockParams.context,
+ }));
+ vi.spyOn(svc as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });
+ vi.spyOn((svc as any).messageService, 'prepareUiMessages').mockResolvedValue([]);
+ (svc as any).messageModel.query = vi.fn().mockResolvedValue([]);
+ 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());
+ coordinator.getOperationMetadata.mockResolvedValue(mockMetadata);
+ return { coordinator, step };
+ };
+
+ it('runs the init, saves what it produced, and steps on the initialized state', async () => {
+ const initContext = { phase: 'user_input', payload: { assembled: true } };
+ const runDeferredInit = vi.fn().mockResolvedValue({
+ context: initContext,
+ state: {
+ operationToolSet: { enabledToolIds: ['lobe-web-browsing'] },
+ world: { agent: { systemRole: 'ready' } },
+ },
+ });
+ const svc = buildService(runDeferredInit);
+ const { coordinator, step } = wireStep(svc);
+
+ await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ expect(runDeferredInit).toHaveBeenCalledTimes(1);
+ expect(runDeferredInit.mock.calls[0][0]).toMatchObject({
+ operationId: 'test-operation-1',
+ request: { selectedToolIds: ['lobe-web-browsing'] },
+ });
+ // Durable before the step runs, and the marker is gone so a retry of
+ // this delivery cannot pay for discovery twice.
+ const saved = coordinator.saveAgentState.mock.calls[0][1];
+ expect(saved.operationToolSet).toEqual({ enabledToolIds: ['lobe-web-browsing'] });
+ expect(saved.request).toBeUndefined();
+ expect(saved.initialContext).toEqual(initContext);
+ // The exit: the step sees the initialized state, not the thin one.
+ expect(step.mock.calls[0][0].operationToolSet).toEqual({
+ enabledToolIds: ['lobe-web-browsing'],
+ });
+ // ...and the context the init assembled, not the placeholder queued
+ // before the init existed.
+ expect(step.mock.calls[0][1]).toEqual(initContext);
+ });
+
+ // The worker can die after saving the init but before the step runs. The
+ // redelivery finds the request gone β€” and must still start from the
+ // context the init assembled, not the placeholder it was queued with.
+ it('starts a redelivered step 0 from the context the init saved', async () => {
+ const runDeferredInit = vi.fn();
+ const svc = buildService(runDeferredInit);
+ const { coordinator, step } = wireStep(svc);
+ const assembled = { phase: 'user_input', payload: { assembled: true } };
+ const { request: _request, ...initialized } = pendingState();
+ coordinator.loadAgentState.mockResolvedValue({ ...initialized, initialContext: assembled });
+
+ await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ expect(runDeferredInit).not.toHaveBeenCalled();
+ expect(step.mock.calls[0][1]).toEqual(assembled);
+ });
+
+ it('skips the init when the run was already stopped, and still settles it', async () => {
+ const runDeferredInit = vi.fn();
+ const svc = buildService(runDeferredInit);
+ const { coordinator, step } = wireStep(svc);
+ coordinator.isInterrupted.mockResolvedValue(true);
+ const lifecycle = (svc as any).completionLifecycle;
+ const emit = vi.spyOn(lifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ const dispatch = vi.spyOn(lifecycle, 'dispatchHooks').mockResolvedValue(undefined);
+ const publish = vi.spyOn((svc as any).streamManager, 'publishStreamEvent');
+
+ const result = await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ // Persisting the stop already published `agent_runtime_end`: no step
+ // event may follow it.
+ expect(publish).not.toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ type: 'step_start' }),
+ );
+
+ expect(result.success).toBe(true);
+ expect(runDeferredInit).not.toHaveBeenCalled();
+ expect(step).not.toHaveBeenCalled();
+ // The completion consumers (and the durable row) hear about the stop.
+ expect(emit).toHaveBeenCalledWith('test-operation-1', expect.anything(), 'interrupted');
+ expect(dispatch).toHaveBeenCalledWith('test-operation-1', expect.anything(), 'interrupted');
+ // The interrupt may have landed only its sentinel: the runtime state has
+ // to be written too, or Redis keeps reading `running` forever.
+ expect(coordinator.saveAgentState).toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ status: 'interrupted' }),
+ );
+ });
+
+ // Stop finished both writes before the worker loaded the state: it is
+ // already `interrupted` but still carries its request. The stop's own save
+ // published `agent_runtime_end`, so this delivery may publish no step
+ // event and must not persist the stop a second time.
+ it('settles a stop that was fully persisted before the init, without a step_start', async () => {
+ const runDeferredInit = vi.fn();
+ const svc = buildService(runDeferredInit);
+ const { coordinator, step } = wireStep(svc);
+ coordinator.loadAgentState.mockResolvedValue({ ...pendingState(), status: 'interrupted' });
+ const lifecycle = (svc as any).completionLifecycle;
+ const emit = vi.spyOn(lifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ const dispatch = vi.spyOn(lifecycle, 'dispatchHooks').mockResolvedValue(undefined);
+ const publish = vi.spyOn((svc as any).streamManager, 'publishStreamEvent');
+
+ const result = await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ expect(result.success).toBe(true);
+ expect(publish).not.toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ type: 'step_start' }),
+ );
+ expect(runDeferredInit).not.toHaveBeenCalled();
+ expect(step).not.toHaveBeenCalled();
+ expect(coordinator.saveAgentState).not.toHaveBeenCalled();
+ expect(emit).toHaveBeenCalledWith('test-operation-1', expect.anything(), 'interrupted');
+ expect(dispatch).toHaveBeenCalledWith('test-operation-1', expect.anything(), 'interrupted');
+ });
+
+ it('discards the init result when Stop lands while the init runs', async () => {
+ const runDeferredInit = vi.fn().mockResolvedValue({
+ context: { phase: 'user_input', payload: {} },
+ state: { operationToolSet: { enabledToolIds: ['lobe-web-browsing'] } },
+ });
+ const svc = buildService(runDeferredInit);
+ const { coordinator, step } = wireStep(svc);
+ coordinator.isInterrupted.mockResolvedValueOnce(false).mockResolvedValue(true);
+ const lifecycle = (svc as any).completionLifecycle;
+ vi.spyOn(lifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ vi.spyOn(lifecycle, 'dispatchHooks').mockResolvedValue(undefined);
+ const publish = vi.spyOn((svc as any).streamManager, 'publishStreamEvent');
+
+ await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ expect(runDeferredInit).toHaveBeenCalledTimes(1);
+ expect(step).not.toHaveBeenCalled();
+ expect(publish).not.toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ type: 'step_start' }),
+ );
+ // Nothing wrote the pre-init `running` state back over the stop.
+ for (const [, saved] of coordinator.saveAgentState.mock.calls) {
+ expect(saved.status).toBe('interrupted');
+ expect(saved.operationToolSet).toBeUndefined();
+ }
+ });
+
+ // Stop can land after the post-init checks but before the init's save,
+ // which then overwrites the interrupted state with `running`. The stop
+ // already published `agent_runtime_end`, so the save must be undone and
+ // no step event may follow.
+ it('restores a stop that landed while the init result was being saved', async () => {
+ const runDeferredInit = vi.fn().mockResolvedValue({
+ context: { phase: 'user_input', payload: {} },
+ state: { operationToolSet: { enabledToolIds: ['lobe-web-browsing'] } },
+ });
+ const svc = buildService(runDeferredInit);
+ const { coordinator, step } = wireStep(svc);
+ // Clear before the init and at the post-init check; set right after the save.
+ coordinator.isInterrupted
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(false)
+ .mockResolvedValue(true);
+ vi.spyOn((svc as any).agentOperationModel, 'findById').mockResolvedValue({
+ id: 'test-operation-1',
+ status: 'running',
+ });
+ const lifecycle = (svc as any).completionLifecycle;
+ vi.spyOn(lifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ const dispatch = vi.spyOn(lifecycle, 'dispatchHooks').mockResolvedValue(undefined);
+ const publish = vi.spyOn((svc as any).streamManager, 'publishStreamEvent');
+
+ const result = await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ expect(result.success).toBe(true);
+ expect(step).not.toHaveBeenCalled();
+ expect(publish).not.toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ type: 'step_start' }),
+ );
+ // The last write leaves the run interrupted, not `running`.
+ const saves = coordinator.saveAgentState.mock.calls;
+ expect(saves.at(-1)[1]).toMatchObject({ status: 'interrupted' });
+ expect(dispatch).toHaveBeenCalledWith('test-operation-1', expect.anything(), 'interrupted');
+ });
+
+ // The init can outlive the inactivity watchdog. Abandonment settles the
+ // run itself and may delete the runtime state; this worker must not save
+ // its stale `running` snapshot back and step on it.
+ describe('when the run is abandoned while the init runs', () => {
+ const runAbandonedDuringInit = async (
+ arrange: (ctx: { coordinator: any; findById: any }) => void,
+ ) => {
+ const runDeferredInit = vi.fn().mockResolvedValue({
+ context: { phase: 'user_input', payload: {} },
+ state: { operationToolSet: { enabledToolIds: ['lobe-web-browsing'] } },
+ });
+ const svc = buildService(runDeferredInit);
+ const { coordinator, step } = wireStep(svc);
+ coordinator.isInterrupted.mockResolvedValue(false);
+ const findById = vi
+ .spyOn((svc as any).agentOperationModel, 'findById')
+ .mockResolvedValue({ id: 'test-operation-1', status: 'running' });
+ arrange({ coordinator, findById });
+ const publish = vi.spyOn((svc as any).streamManager, 'publishStreamEvent');
+
+ const result = await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ expect(runDeferredInit).toHaveBeenCalledTimes(1);
+ expect(result).toMatchObject({ nextStepScheduled: false, success: true });
+ expect(coordinator.saveAgentState).not.toHaveBeenCalled();
+ expect(step).not.toHaveBeenCalled();
+ expect(publish).not.toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ type: 'step_start' }),
+ );
+ };
+
+ it('discards the init result when the runtime state was deleted', async () => {
+ await runAbandonedDuringInit(({ coordinator }) => {
+ coordinator.loadAgentState.mockResolvedValueOnce(pendingState()).mockResolvedValue(null);
+ });
+ });
+
+ it('discards the init result when the durable row turned terminal', async () => {
+ await runAbandonedDuringInit(({ findById }) => {
+ findById
+ .mockResolvedValueOnce({ id: 'test-operation-1', status: 'running' })
+ .mockResolvedValue({ id: 'test-operation-1', status: 'error' });
+ });
+ });
+ });
+
+ it('does not initialize a shared run whose share was revoked after enqueue', async () => {
+ const runDeferredInit = vi.fn();
+ const verifyShareRunStillAuthorized = vi.fn().mockResolvedValue(false);
+ const svc = new AgentRuntimeService(mockDb, mockUserId, {
+ delegate: { runDeferredInit, verifyShareRunStillAuthorized },
+ });
+ const { coordinator, step } = wireStep(svc);
+ coordinator.loadAgentState.mockResolvedValue({
+ ...pendingState(),
+ principal: { actor: { shareVisitor: { agentId: 'agent-1', shareId: 'share-1' } } },
+ });
+ vi.spyOn(svc as any, 'buildShareAbortResult').mockResolvedValue({ success: true });
+
+ await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ expect(verifyShareRunStillAuthorized).toHaveBeenCalled();
+ expect(runDeferredInit).not.toHaveBeenCalled();
+ expect(step).not.toHaveBeenCalled();
+ });
+
+ it('fails the step when the init throws instead of stepping on a thin state', async () => {
+ const runDeferredInit = vi.fn().mockRejectedValue(new Error('discovery exploded'));
+ const svc = buildService(runDeferredInit);
+ const { step } = wireStep(svc);
+
+ await expect(svc.executeStep({ ...mockParams, stepIndex: 0 })).rejects.toThrow(
+ 'discovery exploded',
+ );
+ expect(step).not.toHaveBeenCalled();
+ });
+
+ // A Stop that lands while the init awaits its I/O, followed by that I/O
+ // failing, is still a stop: the failure must not reach the step error
+ // handler, which would overwrite `interrupted` with `error`.
+ it('settles a stop that landed before the init rejected as interrupted, not as an error', async () => {
+ const runDeferredInit = vi.fn().mockRejectedValue(new Error('discovery exploded'));
+ const svc = buildService(runDeferredInit);
+ const { coordinator, step } = wireStep(svc);
+ coordinator.isInterrupted.mockResolvedValueOnce(false).mockResolvedValue(true);
+ const lifecycle = (svc as any).completionLifecycle;
+ vi.spyOn(lifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ const dispatch = vi.spyOn(lifecycle, 'dispatchHooks').mockResolvedValue(undefined);
+ const publish = vi.spyOn((svc as any).streamManager, 'publishStreamEvent');
+
+ await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ expect(step).not.toHaveBeenCalled();
+ for (const [, saved] of coordinator.saveAgentState.mock.calls) {
+ expect(saved.status).toBe('interrupted');
+ }
+ expect(dispatch).toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ status: 'interrupted' }),
+ 'interrupted',
+ );
+ expect(publish).not.toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ type: 'error' }),
+ );
+ });
+
+ it('drops a rejected init of a run that was abandoned meanwhile instead of failing it', async () => {
+ const runDeferredInit = vi.fn().mockRejectedValue(new Error('discovery exploded'));
+ const svc = buildService(runDeferredInit);
+ const { coordinator, step } = wireStep(svc);
+ coordinator.isInterrupted.mockResolvedValue(false);
+ vi.spyOn((svc as any).agentOperationModel, 'findById')
+ .mockResolvedValueOnce({ id: 'test-operation-1', status: 'running' })
+ .mockResolvedValue({ id: 'test-operation-1', status: 'abandoned' });
+
+ const result = await svc.executeStep({ ...mockParams, stepIndex: 0 });
+
+ expect(result).toMatchObject({ nextStepScheduled: false, success: true });
+ expect(coordinator.saveAgentState).not.toHaveBeenCalled();
+ expect(step).not.toHaveBeenCalled();
+ });
+
+ it('refuses to run when no runner is wired', async () => {
+ const svc = buildService(undefined);
+ const { step } = wireStep(svc);
+
+ await expect(svc.executeStep({ ...mockParams, stepIndex: 0 })).rejects.toThrow(
+ /no runner is wired/,
+ );
+ expect(step).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/deferredInit.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/deferredInit.ts
new file mode 100644
index 00000000000..ad2465b1a1c
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/deferredInit.ts
@@ -0,0 +1,247 @@
+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';
+import type { AgentRunInitRequest } from '@lobechat/types';
+import debug from 'debug';
+
+import type { AgentOperationModel } from '@/database/models/agentOperation';
+import type { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';
+
+import type { AgentExecutionResult } from '../../types';
+import { isTerminalAgentStatus, loadTerminalDurableStatus } from '../terminalStatus';
+
+const log = debug('lobe-server:agent-runtime-service');
+
+/**
+ * Run the init an operation was created without: tool discovery and the
+ * message / context assembly for `state.request`. Returns the state slots they
+ * produce, which the step merges before executing.
+ *
+ * Implemented by AiAgentService (it owns the pipeline and the models it needs);
+ * the runtime only knows when to ask and what to do with the answer.
+ */
+export type DeferredInitRunner = (params: {
+ operationId: string;
+ request: AgentRunInitRequest;
+ state: AgentState;
+}) => Promise<{
+ /**
+ * The context step 0 must run with. The step was queued before the init
+ * existed, so the context it carries is a placeholder β€” the assembled base
+ * context (and an approval resume's phase) only exists after init.
+ */
+ context: AgentRuntimeContext;
+ state: Partial<AgentState>;
+}>;
+
+export interface DeferredInitDeps {
+ /** Terminate a shared run whose authorization was revoked. */
+ abortShareRun: (state: AgentState) => Promise<AgentExecutionResult>;
+ agentOperationModel: AgentOperationModel;
+ coordinator: AgentRuntimeCoordinator;
+ isShareRunRevoked: (state: AgentState) => Promise<boolean>;
+ runDeferredInit?: DeferredInitRunner;
+ /** Settle a step that will not run: completion signals and hooks, no step event. */
+ settleSkippedStep: (state: AgentState) => Promise<AgentExecutionResult>;
+}
+
+/** Either the step ends here with `result`, or it proceeds with `context` (when the init ran). */
+export type DeferredInitOutcome =
+ | { context: AgentRuntimeContext; result?: undefined }
+ | { context?: undefined; result: AgentExecutionResult };
+
+/**
+ * Make a stop that landed before (or during) a deferred init durable. The
+ * interrupt may have written only its sentinel before crashing, and the
+ * completion lifecycle does not own the runtime-state transition: the
+ * coordinator save does, and it is also what publishes `agent_runtime_end`
+ * exactly once. Idempotent for a state that is already interrupted.
+ */
+const persistStopBeforeInit = async (
+ coordinator: AgentRuntimeCoordinator,
+ operationId: string,
+ state: AgentState,
+): Promise<void> => {
+ const alreadyPersisted =
+ (await coordinator.loadAgentState(operationId))?.status === 'interrupted';
+ state.status = 'interrupted';
+ if (alreadyPersisted) return;
+ await coordinator.saveAgentState(operationId, {
+ ...state,
+ lastModified: new Date().toISOString(),
+ status: 'interrupted',
+ });
+};
+
+/**
+ * Whether the run stopped being this worker's while its init was awaited, and
+ * if so, the outcome that settles it. Stop can land during the init, and the
+ * abort poll is not armed yet: saving this worker's pre-init `running` state
+ * would overwrite the interrupted one and walk straight into LLM work, so
+ * re-read before writing anything. The init can also outlive the inactivity
+ * watchdog: abandonment (or a recovery that replaced this run) settles the
+ * operation, its lifecycle included, and may delete the runtime state. A
+ * missing state, a terminal one, or a terminal durable row all mean the run is
+ * no longer this worker's.
+ */
+const settleIfReleasedDuringInit = async (
+ deps: DeferredInitDeps,
+ {
+ agentState,
+ operationId,
+ stepIndex,
+ }: { agentState: AgentState; operationId: string; stepIndex: number },
+ initOutcome: 'failed' | 'finished',
+): Promise<DeferredInitOutcome | undefined> => {
+ const { coordinator } = deps;
+ const latest = await coordinator.loadAgentState(operationId);
+ if ((await coordinator.isInterrupted(operationId)) || latest?.status === 'interrupted') {
+ log(
+ '[%s][%d] Interrupted while the deferred init ran (init %s); settling the stop',
+ operationId,
+ stepIndex,
+ initOutcome,
+ );
+ await persistStopBeforeInit(coordinator, operationId, latest ?? agentState);
+ Object.assign(agentState, latest ?? {}, { status: 'interrupted' });
+ return { result: await deps.settleSkippedStep(agentState) };
+ }
+
+ const endedStatus = !latest
+ ? 'missing'
+ : isTerminalAgentStatus(latest.status)
+ ? latest.status
+ : await loadTerminalDurableStatus(deps.agentOperationModel, operationId, stepIndex);
+ if (endedStatus) {
+ log(
+ '[%s][%d] Operation ended while the deferred init ran (%s, init %s); dropping it',
+ operationId,
+ stepIndex,
+ endedStatus,
+ initOutcome,
+ );
+ return {
+ result: { nextStepScheduled: false, state: latest ?? {}, stepResult: null, success: true },
+ };
+ }
+
+ return undefined;
+};
+
+/**
+ * The run may have been created without its init β€” the send path returned as
+ * soon as the messages were durable and left discovery and the context
+ * assembly to this worker. The turn's request is still on the state, which is
+ * exactly what says the init has not run yet; call this only when it is.
+ *
+ * It runs after the step claim, so two deliveries of step 0 cannot both pay for
+ * a discovery, and before anything is published, so the client sees one
+ * `step_start` for a fully initialized run. A failure here rejects into the
+ * step error handler: the operation ends with the error on its assistant
+ * message, which is the only honest outcome once the user has already been told
+ * the message was sent.
+ *
+ * Mutates `agentState` in place, as the step does with the state it loaded.
+ */
+export const runPendingInit = async (
+ deps: DeferredInitDeps,
+ params: {
+ agentState: AgentState;
+ operationId: string;
+ /** The turn's request still on `agentState`. */
+ request: AgentRunInitRequest;
+ stepIndex: number;
+ },
+): Promise<DeferredInitOutcome> => {
+ const { coordinator } = deps;
+ const { agentState, operationId, request, stepIndex } = params;
+
+ if (isTerminalAgentStatus(agentState.status)) {
+ // The run ended before its init ran β€” typically a Stop whose writes
+ // all landed first. That save already published
+ // `agent_runtime_end`, so settle here, before `step_start`, and do
+ // not persist the terminal state a second time.
+ log(
+ '[%s][%d] Operation already %s before deferred init; skipping it',
+ operationId,
+ stepIndex,
+ agentState.status,
+ );
+ return { result: await deps.settleSkippedStep(agentState) };
+ }
+
+ if (await coordinator.isInterrupted(operationId)) {
+ // Stop pressed during the init window. Skip the discovery nobody is
+ // waiting for, but still settle the run: the state may read
+ // `running` if the interrupt landed only its sentinel before a
+ // crash. Return before `step_start` β€” persisting the stop publishes
+ // `agent_runtime_end`, and no step event may follow it.
+ log('[%s][%d] Interrupted before deferred init; skipping it', operationId, stepIndex);
+ await persistStopBeforeInit(coordinator, operationId, agentState);
+ return { result: await deps.settleSkippedStep(agentState) };
+ }
+
+ // A shared-agent run revoked between enqueue and step 0 must not
+ // get creator-scoped discovery and history/persona assembly first:
+ // the per-step authorization re-check comes too late for that.
+ if (await deps.isShareRunRevoked(agentState)) {
+ return { result: await deps.abortShareRun(agentState) };
+ }
+
+ if (!deps.runDeferredInit) {
+ throw new Error(`Operation ${operationId} needs a deferred init but no runner is wired`);
+ }
+
+ const initStartedAt = Date.now();
+ let initialized: Awaited<ReturnType<DeferredInitRunner>>;
+ try {
+ initialized = await deps.runDeferredInit({
+ operationId,
+ request,
+ state: agentState,
+ });
+ } catch (error) {
+ // A failure is only this worker's to report while it still owns the run.
+ // A Stop (or an abandonment) that landed while the init was awaited wins:
+ // the step error handler would overwrite it with `error`.
+ const released = await settleIfReleasedDuringInit(deps, params, 'failed');
+ if (released) return released;
+ throw error;
+ }
+
+ const released = await settleIfReleasedDuringInit(deps, params, 'finished');
+ if (released) return released;
+
+ // One write: the initialized slots, the assembled context (a
+ // redelivery after this save finds the request gone and must still
+ // start from it), and the cleared request (so that redelivery does
+ // not pay for discovery again).
+ Object.assign(agentState, initialized.state, {
+ initialContext: initialized.context,
+ request: undefined,
+ });
+ await coordinator.saveAgentState(operationId, agentState);
+
+ // The checks above and this save are not atomic: a Stop landing in
+ // between has already written its sentinel and interrupted state
+ // (publishing `agent_runtime_end`), which the save just overwrote
+ // with `running`. Re-check the sentinel once more and, if it is
+ // set, put the stop back and settle without a step event. A Stop
+ // after this point lands on the saved state and is handled like
+ // any Stop during a step.
+ if (await coordinator.isInterrupted(operationId)) {
+ log(
+ '[%s][%d] Interrupted while the deferred init was saved; restoring the stop',
+ operationId,
+ stepIndex,
+ );
+ await persistStopBeforeInit(coordinator, operationId, agentState);
+ return { result: await deps.settleSkippedStep(agentState) };
+ }
+
+ log(
+ '[%s][%d] Deferred init finished in %dms',
+ operationId,
+ stepIndex,
+ Date.now() - initStartedAt,
+ );
+ return { context: initialized.context };
+};
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts
index d11bb3ee014..3ffeb5a4db3 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts
@@ -3,6 +3,8 @@ import debug from 'debug';
import { type AgentExecutionParams, type AgentExecutionResult } from '../../types';
import { STEP_LOCK_RETRY_MAX_ATTEMPTS } from '../constants';
+import { isShareRunRevoked } from '../shareRunGate';
+import { loadTerminalDurableStatus } from '../terminalStatus';
import type { AgentRuntimeServiceContext } from '../types';
import { stepLockRetryDelayMs } from '../utils';
@@ -74,31 +76,26 @@ export async function runLockFreeDelivery(
// marked that operation interrupted. ACK it without touching the old
// topic; otherwise the abandoned attempt can finish concurrently with its
// replacement and submit a second Acceptance run.
- try {
- const durableOperation = await deps.agentOperationModel.findById(operationId);
- if (
- durableOperation &&
- ['done', 'error', 'interrupted', 'abandoned'].includes(durableOperation.status)
- ) {
- log(
- '[%s][%d] Skipping delivery for terminal durable operation (%s)',
- operationId,
- stepIndex,
- durableOperation.status,
- );
- return {
- nextStepScheduled: false,
- state: {
- status: durableOperation.status === 'abandoned' ? 'interrupted' : durableOperation.status,
- },
- stepResult: null,
- success: true,
- };
- }
- } catch (error) {
- // Preserve runtime availability when the durable store has a transient
- // read failure. The step lock and normal persistence path still apply.
- log('[%s][%d] Durable operation status check failed: %O', operationId, stepIndex, error);
+ const durableTerminalStatus = await loadTerminalDurableStatus(
+ deps.agentOperationModel,
+ operationId,
+ stepIndex,
+ );
+ if (durableTerminalStatus) {
+ log(
+ '[%s][%d] Skipping delivery for terminal durable operation (%s)',
+ operationId,
+ stepIndex,
+ durableTerminalStatus,
+ );
+ return {
+ nextStepScheduled: false,
+ state: {
+ status: durableTerminalStatus === 'abandoned' ? 'interrupted' : durableTerminalStatus,
+ },
+ stepResult: null,
+ success: true,
+ };
}
// Watchdog re-check for a parked async-tool wait: re-run the barrier + CAS
@@ -401,19 +398,7 @@ export async function skipUnrunnableStep(
agentState.status,
);
- const reason = deps.determineCompletionReason(agentState);
-
- await deps.completionLifecycle.emitSignalEvents(operationId, agentState, reason);
-
- // Dispatch completion hooks so consumers (e.g., bot local-mode promise) can finalize
- await deps.completionLifecycle.dispatchHooks(operationId, agentState, reason);
-
- return {
- nextStepScheduled: false,
- state: agentState,
- stepResult: null,
- success: true,
- };
+ return settleSkippedStep(deps, operationId, agentState);
}
// A run parked for a client moves only through its own resume: any other
@@ -439,27 +424,39 @@ export async function skipUnrunnableStep(
// step boundary. See `AgentShareModel.isRunStillAuthorized`'s JSDoc for
// why one query covers every revocation path (visibility flip β€” which
// is what turning sharing off does β€” share delete, agent delete).
- if (deps.delegate.verifyShareRunStillAuthorized) {
- const shareMarker = agentState.principal?.actor?.shareVisitor as
- { agentId?: string; shareId?: string } | undefined;
- if (shareMarker?.agentId && shareMarker.shareId) {
- let stillAuthorized = false;
- try {
- stillAuthorized = await deps.delegate.verifyShareRunStillAuthorized({
- agentId: shareMarker.agentId,
- shareId: shareMarker.shareId,
- });
- } catch (error) {
- // Fail closed: a read failure must not be read as "still
- // authorized". Falls through to the abort below with
- // `stillAuthorized` left `false`.
- log('[%s][%d] Share run authorization re-check failed: %O', operationId, stepIndex, error);
- }
- if (!stillAuthorized) {
- return deps.buildShareAbortResult(operationId, agentState);
- }
- }
+ if (
+ await isShareRunRevoked(
+ deps.delegate.verifyShareRunStillAuthorized,
+ operationId,
+ stepIndex,
+ agentState,
+ )
+ ) {
+ return deps.buildShareAbortResult(operationId, agentState);
}
return undefined;
}
+
+/**
+ * Settle a step that will not run because the operation is already terminal:
+ * emit the completion signals and dispatch the completion hooks so consumers
+ * (e.g. the bot local-mode promise) can finalize. Publishes no step event.
+ */
+export async function settleSkippedStep(
+ deps: Pick<StepGuardsDeps, 'completionLifecycle' | 'determineCompletionReason'>,
+ operationId: string,
+ agentState: AgentState,
+): Promise<AgentExecutionResult> {
+ const reason = deps.determineCompletionReason(agentState);
+
+ await deps.completionLifecycle.emitSignalEvents(operationId, agentState, reason);
+ await deps.completionLifecycle.dispatchHooks(operationId, agentState, reason);
+
+ return {
+ nextStepScheduled: false,
+ state: agentState,
+ stepResult: null,
+ success: true,
+ };
+}
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
index 0138c3885a3..29924f6e3ee 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
@@ -1,4 +1,4 @@
-import { getLlmCallCount } from '@lobechat/agent-runtime';
+import { type AgentRuntimeContext, getLlmCallCount } from '@lobechat/agent-runtime';
import { context as otelContext, trace as otelTrace } from '@lobechat/observability-otel/api';
import {
buildInvokeAgentAttributes,
@@ -14,16 +14,19 @@ import {
type AgentStepContinuation,
} from '../../types';
import { STEP_LOCK_TTL_SECONDS } from '../constants';
+import { isShareRunRevoked } from '../shareRunGate';
import type { AgentRuntimeServiceContext } from '../types';
import { createStepLockOwner } from '../utils';
import { startStepAbortPoll, type StepAbortPoll } from './abortPoll';
import { finishOperation } from './completion';
import { scheduleNextStep } from './continuation';
+import { runPendingInit } from './deferredInit';
import { failStep } from './failure';
import {
handleStepLockConflict,
replayPendingInterventionLifecycle,
runLockFreeDelivery,
+ settleSkippedStep,
skipUnrunnableStep,
} from './guards';
import { dispatchAfterStepHooks, dispatchBeforeStepHooks, persistStepTracking } from './hooks';
@@ -146,6 +149,31 @@ export async function executeStep(
throw new Error(`Agent state not found for operation ${operationId}`);
}
+ // 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.
+ let deferredInitContext: AgentRuntimeContext | undefined;
+ if (agentState.request) {
+ const init = await runPendingInit(
+ {
+ abortShareRun: (state) => deps.buildShareAbortResult(operationId, state),
+ agentOperationModel: deps.agentOperationModel,
+ coordinator: deps.coordinator,
+ isShareRunRevoked: (state) =>
+ isShareRunRevoked(
+ deps.delegate.verifyShareRunStillAuthorized,
+ operationId,
+ stepIndex,
+ state,
+ ),
+ runDeferredInit: deps.delegate.runDeferredInit,
+ settleSkippedStep: (state) => settleSkippedStep(deps, operationId, state),
+ },
+ { agentState, operationId, request: agentState.request, stepIndex },
+ );
+ if (init.result) return init.result;
+ deferredInitContext = init.context;
+ }
+
const replayed = await replayPendingInterventionLifecycle(deps, {
agentState,
externalRetryCount,
@@ -234,7 +262,12 @@ export async function executeStep(
},
});
- const input = await prepareStepInput(deps, { agentState, params, stepEntryMessages });
+ const input = await prepareStepInput(deps, {
+ agentState,
+ deferredInitContext,
+ params,
+ stepEntryMessages,
+ });
const { currentContext } = input;
const { startAt, stepResult } = await runAndReconcileStep(deps, {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts
index 2d69bd41d68..3bdc4c69066 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts
@@ -56,10 +56,13 @@ export async function prepareStepInput(
deps: StepPrepareDeps,
{
agentState,
+ deferredInitContext,
params,
stepEntryMessages,
}: {
agentState: AgentState;
+ /** The context a deferred init assembled in this delivery, if one ran. */
+ deferredInitContext?: AgentExecutionParams['context'];
params: AgentExecutionParams;
stepEntryMessages: Awaited<
ReturnType<AgentRuntimeServiceContext['queryStepEntryMessages']>
@@ -80,8 +83,16 @@ export async function prepareStepInput(
toolMessageId,
} = params;
+ // Step 0 starts from the operation's saved initial context β€” the same rule
+ // `executeSync` follows. For an ordinary run it is the context that was
+ // queued; for a deferred init it is the one the init assembled, which the
+ // queued placeholder predates, including on a redelivery after the save.
+ const savedInitialContext = (
+ agentState as AgentState & { initialContext?: AgentExecutionParams['context'] }
+ ).initialContext;
// Handle human intervention
- let currentContext = context;
+ let currentContext =
+ deferredInitContext ?? (stepIndex === 0 ? (savedInitialContext ?? context) : context);
// The wait this step resumes, if any: a resumed call that finds no client
// again re-parks under the same deadline, so retries never extend it.
let resumedClientLlmWait: AgentRunClientLlmWait | undefined;
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/shareRunGate.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/shareRunGate.ts
index ae3262d9b03..6d489619e11 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/shareRunGate.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/shareRunGate.ts
@@ -2,7 +2,7 @@ import type { AgentState } from '@lobechat/agent-runtime';
import debug from 'debug';
import { type AgentExecutionResult } from '../types';
-import type { AgentRuntimeServiceContext } from './types';
+import type { AgentRuntimeDelegate, AgentRuntimeServiceContext } from './types';
const log = debug('lobe-server:agent-runtime-service');
@@ -12,6 +12,28 @@ export type ShareRunGateDeps = Pick<
'completionLifecycle' | 'coordinator' | 'interruptOperation'
>;
+/**
+ * Whether an Agent Share visitor run has lost its authorization. Fails closed:
+ * a read failure is treated as revoked. Non-share runs are never revoked.
+ */
+export async function isShareRunRevoked(
+ verify: AgentRuntimeDelegate['verifyShareRunStillAuthorized'],
+ operationId: string,
+ stepIndex: number,
+ agentState: AgentState,
+): Promise<boolean> {
+ if (!verify) return false;
+ const shareMarker = agentState.principal?.actor?.shareVisitor as
+ { agentId?: string; shareId?: string } | undefined;
+ if (!shareMarker?.agentId || !shareMarker.shareId) return false;
+ try {
+ return !(await verify({ agentId: shareMarker.agentId, shareId: shareMarker.shareId }));
+ } catch (error) {
+ log('[%s][%d] Share run authorization re-check failed: %O', operationId, stepIndex, error);
+ return true;
+ }
+}
+
/**
* Terminate an Agent Share visitor run whose authorization was revoked
* mid-flight (see the per-step check in `executeStep`).
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/terminalStatus.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/terminalStatus.ts
new file mode 100644
index 00000000000..49643833a1f
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/terminalStatus.ts
@@ -0,0 +1,37 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import debug from 'debug';
+
+import type { AgentOperationModel } from '@/database/models/agentOperation';
+
+const log = debug('lobe-server:agent-runtime-service');
+
+export const isTerminalAgentStatus = (status: AgentState['status'] | undefined) =>
+ status === 'done' || status === 'error' || status === 'interrupted';
+
+/**
+ * The durable operation row's status when it is terminal, else `undefined`.
+ * Redis keeps the resumable step state, but the row is the authority for
+ * cancellation, abandonment and recovery. A read failure preserves runtime
+ * availability: it reads as not terminal, and the step lock and the normal
+ * persistence path still apply.
+ */
+export const loadTerminalDurableStatus = async (
+ agentOperationModel: AgentOperationModel,
+ operationId: string,
+ stepIndex: number,
+): Promise<'abandoned' | 'done' | 'error' | 'interrupted' | undefined> => {
+ try {
+ const status = (await agentOperationModel.findById(operationId))?.status;
+ if (
+ status === 'done' ||
+ status === 'error' ||
+ status === 'interrupted' ||
+ status === 'abandoned'
+ ) {
+ return status;
+ }
+ } catch (error) {
+ log('[%s][%d] Durable operation status check failed: %O', operationId, stepIndex, error);
+ }
+ return undefined;
+};
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts
index 238c36d72fe..6d291c2c708 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts
@@ -41,6 +41,7 @@ import type {
updateAssistantRowWithRetry,
} from './clientLlmWait';
import type { createOperation } from './createOperation';
+import type { DeferredInitRunner } from './executeStep/deferredInit';
import type { executeStep } from './executeStep/index';
import type { executeSync } from './executeSync';
import type {
@@ -158,6 +159,8 @@ export interface AgentRuntimeDelegate {
scope: SteerQueueScope;
state: AgentState;
}) => Promise<{ messageId: string } | undefined>;
+ /** Run the init an operation was created without (see `DeferredInitRunner`). */
+ runDeferredInit?: DeferredInitRunner;
/**
* A top-level run just finished: start the follow-ups the user queued behind
* it as the next turn (the composer pipeline, with `steer`). Resolves to
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts
index 817d01f0faa..41e0fcbdcea 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts
@@ -1,6 +1,11 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
-import { buildOperationInitRequest, type OperationInitRequest } from '../operationInit';
+import {
+ buildOperationInitRequest,
+ type OperationInitRequest,
+ rehydrateDetachedFileContent,
+ toPersistedInitRequest,
+} from '../operationInit';
const fullInput = (): Parameters<typeof buildOperationInitRequest>[0] => ({
additionalPluginIds: ['lobe-task'],
@@ -22,13 +27,9 @@ const fullInput = (): Parameters<typeof buildOperationInitRequest>[0] => ({
},
] as any,
attachedFileIds: ['file-1'],
- botContext: { platform: 'discord' } as any,
- botPlatformContext: { platformName: 'discord', supportsMarkdown: false } as any,
disableLocalSystem: false,
disableSelfFeedbackIntentTool: false,
disableTools: false,
- disabledPluginIds: ['lobe-web-browsing'],
- discordContext: { guildId: 'guild-1' },
ephemeralUserMessage: 'ephemeral',
exclusivePluginIds: undefined,
files: [
@@ -41,7 +42,6 @@ const fullInput = (): Parameters<typeof buildOperationInitRequest>[0] => ({
isFixedDeviceTarget: false,
localDeviceId: 'device-1',
mentionedAgents: [{ id: 'agt_2', name: 'Fox' }],
- operationId: 'op-1',
parentMessageId: 'msg-parent',
requestTrigger: 'chat' as any,
requestedDeviceId: 'device-2',
@@ -99,3 +99,51 @@ describe('buildOperationInitRequest', () => {
expect(roundTripped).toEqual(request);
});
});
+
+describe('persisted init request', () => {
+ const withDocuments = (): OperationInitRequest =>
+ buildOperationInitRequest({
+ ...fullInput(),
+ runAttachments: {
+ fileList: [
+ {
+ content: 'x'.repeat(1024),
+ fileType: 'application/pdf',
+ id: 'file-parsed',
+ name: 'a.pdf',
+ size: 1,
+ url: 'u',
+ },
+ { fileType: 'application/pdf', id: 'file-unparsed', name: 'b.pdf', size: 1, url: 'u' },
+ ] as any,
+ warnings: [],
+ },
+ });
+
+ // A parsed attachment can run to tens of MB; the state is one Redis write.
+ it('leaves parsed bodies in the documents table and records which ones', () => {
+ const persisted = toPersistedInitRequest(withDocuments());
+
+ expect(persisted.runAttachments.fileList?.every((file) => file.content === undefined)).toBe(
+ true,
+ );
+ expect(persisted.detachedFileContentIds).toEqual(['file-parsed']);
+ });
+
+ it('reads back only the bodies it detached', async () => {
+ const readFileContent = vi.fn(async (fileId: string) => `body of ${fileId}`);
+
+ const restored = await rehydrateDetachedFileContent(
+ toPersistedInitRequest(withDocuments()),
+ readFileContent,
+ );
+
+ expect(restored.runAttachments.fileList?.map((file) => file.content)).toEqual([
+ 'body of file-parsed',
+ undefined,
+ ]);
+ // The file whose parse failed at turn setup must not be re-parsed here.
+ expect(readFileContent).toHaveBeenCalledTimes(1);
+ expect('detachedFileContentIds' in restored).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 0bd244164ce..5c5b7d72d7a 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -1,6 +1,7 @@
import type { SandboxStorageClaim } from '@lobechat/builtin-tool-cloud-sandbox';
import type { LobeChatDatabase } from '@lobechat/database';
import type { AgentSenderMetadata, ExecAgentResult, UserInterventionConfig } from '@lobechat/types';
+import { agentShareFileAccessScope, ordinaryFileAccessScope } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import debug from 'debug';
@@ -20,6 +21,7 @@ import type { AgentDocumentsService } from '@/server/services/agentDocuments';
import type { AgentRuntimeService } from '@/server/services/agentRuntime';
import { getAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';
import type { ComposioService } from '@/server/services/composio';
+import { DocumentService } from '@/server/services/document';
import type { MarketService } from '@/server/services/market';
import { createRunFacts, type RunFacts } from '../runFacts';
@@ -462,8 +464,12 @@ export const execAgentTurn = async (
}
: appContext,
assistantMessageId: turn.assistantMessageId,
+ botContext,
+ botPlatformContext,
canUseDevice,
deviceAccessReason,
+ disabledPluginIds,
+ discordContext,
model,
parentMessageId,
persistAgentId,
@@ -574,13 +580,9 @@ export const execAgentTurn = async (
approvalOwnerAssistantId,
approvedToolEntries,
attachedFileIds,
- botContext,
- botPlatformContext,
disableLocalSystem,
disableSelfFeedbackIntentTool: params.disableSelfFeedbackIntentTool,
disableTools: params.disableTools,
- disabledPluginIds,
- discordContext,
ephemeralUserMessage,
exclusivePluginIds,
files,
@@ -590,7 +592,6 @@ export const execAgentTurn = async (
isFixedDeviceTarget: turn.isFixedDeviceTarget,
localDeviceId,
mentionedAgents,
- operationId,
parentMessageId,
requestTrigger: requestTriggerMetadata.trigger,
requestedDeviceId: turn.requestedDeviceId,
@@ -620,6 +621,13 @@ export const execAgentTurn = async (
loadHistoryMessages,
messageModel: deps.messageModel,
pluginModel: deps.pluginModel,
+ readFileContent: async (fileId) =>
+ (
+ await new DocumentService(deps.db, deps.userId, deps.workspaceId).parseFile(
+ fileId,
+ shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,
+ )
+ ).content ?? undefined,
throwIfExecutionAborted,
topicModel: deps.topicModel,
userId: deps.userId,
@@ -627,6 +635,7 @@ export const execAgentTurn = async (
},
runContext,
initRequest,
+ operationId,
),
);
diff --git a/apps/server/src/services/aiAgent/pipeline/operationInit.ts b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
index 4bf7fa686ac..7570fc9e43c 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationInit.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
@@ -1,5 +1,6 @@
import type { LobeChatDatabase } from '@lobechat/database';
-import type { RequestTrigger } from '@lobechat/types';
+import type { AgentRunInitRequest, RequestTrigger } from '@lobechat/types';
+import pMap from 'p-map';
import type { AgentModel } from '@/database/models/agent';
import type { ConnectorModel } from '@/database/models/connector';
@@ -12,11 +13,7 @@ import type { ComposioService } from '@/server/services/composio';
import type { MarketService } from '@/server/services/market';
import type { ExecRunContext, InternalExecAgentParams } from '../types';
-import {
- type ApprovedToolEntry,
- buildApprovalResumeContext,
- type ClaimedApprovalResume,
-} from './approvalResume';
+import { buildApprovalResumeContext, type ClaimedApprovalResume } from './approvalResume';
import {
type OperationPrepDeps,
type OperationPrepResult,
@@ -24,58 +21,13 @@ import {
} from './operationPrep';
import { traceSendStage } from './sendTracing';
import { discoverTools, type ToolDiscoveryResult } from './toolDiscovery';
-import type { RunAttachments } from './turnSetup';
/**
- * Everything the init stage reads that is NOT a live object: ids, flags and
- * already-resolved values. Plain JSON on purpose β€” an operation that defers its
- * init has to carry this on its state through Redis and rebuild the
- * live half (models, services, the history loader) in the step-0 worker.
- *
- * Keep it that way: a `Date`, a `Buffer` or a model instance in here silently
- * degrades once the request round-trips as JSON. `buildOperationInitRequest` has
- * a test that holds the line.
+ * The turn's raw ask. Declared in `@lobechat/types` because it is also the shape
+ * of `AgentState.request`: a run whose init is deferred carries it there until
+ * the step-0 worker consumes it.
*/
-export interface OperationInitRequest {
- additionalPluginIds?: string[];
- agentSlug?: string | null;
- approvalOwnerAssistantId?: string;
- /** Narrowed from the claim: the entries there carry a `Date` that JSON would flatten. */
- approvedToolEntries: ApprovedToolEntry[];
- attachedFileIds?: string[];
- botContext?: InternalExecAgentParams['botContext'];
- botPlatformContext?: InternalExecAgentParams['botPlatformContext'];
- disabledPluginIds: string[];
- disableLocalSystem?: boolean;
- disableSelfFeedbackIntentTool?: boolean;
- disableTools?: boolean;
- discordContext?: InternalExecAgentParams['discordContext'];
- ephemeralUserMessage?: string;
- exclusivePluginIds?: string[];
- /** Mime types of the raw bot/IM uploads β€” the only thing discovery reads off them. */
- externalFileTypes?: string[];
- functionTools?: InternalExecAgentParams['functionTools'];
- globalMemoryEnabled: boolean;
- hasMentionedAgents: boolean;
- isFixedDeviceTarget: boolean;
- localDeviceId?: string;
- mentionedAgents?: InternalExecAgentParams['mentionedAgents'];
- operationId: string;
- parentMessageId?: string;
- requestedDeviceId?: string;
- requestTrigger?: RequestTrigger;
- resumeApproval?: InternalExecAgentParams['resumeApproval'];
- resumeApprovalPlugin?: Parameters<typeof buildApprovalResumeContext>[0]['resumeApprovalPlugin'];
- resumeApprovals?: InternalExecAgentParams['resumeApprovals'];
- resumeFromHistory: boolean;
- resumeToolResult?: InternalExecAgentParams['resumeToolResult'];
- runAttachments: RunAttachments;
- selectedSkillIds?: string[];
- selectedToolIds?: string[];
- /** The Task this run executes, when it runs inside the Task system. */
- taskId?: string;
- topicBoundDeviceId?: string | null;
-}
+export type OperationInitRequest = AgentRunInitRequest;
/** The live half: models, services and the two loaders the stages call back into. */
export interface OperationInitDeps {
@@ -92,6 +44,12 @@ export interface OperationInitDeps {
loadHistoryMessages: () => Promise<any[]>;
messageModel: MessageModel;
pluginModel: PluginModel;
+ /**
+ * The parsed body of an attachment, read back from the documents table. Only
+ * called for the ids a persisted request detached β€” see
+ * `toPersistedInitRequest`.
+ */
+ readFileContent: (fileId: string) => Promise<string | undefined>;
throwIfExecutionAborted: (stage: string) => Promise<void>;
topicModel: TopicModel;
userId: string;
@@ -131,6 +89,53 @@ export const buildOperationInitRequest = (
};
};
+/**
+ * The request as it may be written to the operation state: parsed attachment
+ * bodies stay in the documents table and only their ids travel. The state is a
+ * single Redis write with a hard size ceiling, and a supported attachment can
+ * parse to tens of MB on its own.
+ */
+export const toPersistedInitRequest = (request: OperationInitRequest): OperationInitRequest => {
+ const fileList = request.runAttachments.fileList;
+ const detached = (fileList ?? []).filter((file) => file.content !== undefined).map((f) => f.id);
+ if (detached.length === 0) return request;
+ return {
+ ...request,
+ detachedFileContentIds: detached,
+ runAttachments: {
+ ...request.runAttachments,
+ fileList: fileList?.map(({ content: _content, ...file }) => file),
+ },
+ };
+};
+
+/**
+ * How many detached bodies are read back at once. Each read hits the documents
+ * table (and may re-parse), and the attachment list is caller-sized.
+ */
+const REHYDRATE_CONCURRENCY = 5;
+
+/**
+ * Put back the bodies `toPersistedInitRequest` detached. Only those ids are
+ * read: a file whose parse failed at turn setup has no body on purpose, and must
+ * not be re-parsed here.
+ */
+export const rehydrateDetachedFileContent = async (
+ request: OperationInitRequest,
+ readFileContent: OperationInitDeps['readFileContent'],
+): Promise<OperationInitRequest> => {
+ const detached = new Set(request.detachedFileContentIds ?? []);
+ if (detached.size === 0 || !request.runAttachments.fileList) return request;
+ const fileList = await pMap(
+ request.runAttachments.fileList,
+ async (file) =>
+ detached.has(file.id) ? { ...file, content: await readFileContent(file.id) } : file,
+ { concurrency: REHYDRATE_CONCURRENCY },
+ );
+ const { detachedFileContentIds: _ids, ...rest } = request;
+ return { ...rest, runAttachments: { ...request.runAttachments, fileList } };
+};
+
/**
* Resolve everything an operation needs before it can take a step: the tool
* surface, the message/context assembly, and the human decision that a resumed
@@ -144,7 +149,10 @@ export const runOperationInit = async (
deps: OperationInitDeps,
ctx: ExecRunContext,
request: OperationInitRequest,
+ operationId: string,
): Promise<OperationInitResult> => {
+ request = await rehydrateDetachedFileContent(request, deps.readFileContent);
+
// Stage 5 (5a–5f) β€” tool discovery (see `pipeline/toolDiscovery`).
const discovery = await traceSendStage('tool_discovery', () =>
discoverTools(
@@ -165,12 +173,12 @@ export const runOperationInit = async (
additionalPluginIds: request.additionalPluginIds,
agentSlug: request.agentSlug,
attachedFileIds: request.attachedFileIds,
- botContext: request.botContext,
+ botContext: ctx.botContext,
disableLocalSystem: request.disableLocalSystem,
disableSelfFeedbackIntentTool: request.disableSelfFeedbackIntentTool,
disableTools: request.disableTools,
- disabledPluginIds: request.disabledPluginIds,
- discordContext: request.discordContext,
+ disabledPluginIds: ctx.disabledPluginIds,
+ discordContext: ctx.discordContext,
exclusivePluginIds: request.exclusivePluginIds,
externalFileTypes: request.externalFileTypes,
functionTools: request.functionTools,
@@ -179,7 +187,7 @@ export const runOperationInit = async (
isFixedDeviceTarget: request.isFixedDeviceTarget,
loadHistoryMessages: deps.loadHistoryMessages,
localDeviceId: request.localDeviceId,
- requestTrigger: request.requestTrigger,
+ requestTrigger: request.requestTrigger as RequestTrigger | undefined,
requestedDeviceId: request.requestedDeviceId,
selectedToolIds: request.selectedToolIds,
throwIfExecutionAborted: deps.throwIfExecutionAborted,
@@ -205,15 +213,15 @@ export const runOperationInit = async (
},
ctx,
{
- botPlatformContext: request.botPlatformContext,
- disabledPluginIds: request.disabledPluginIds,
+ botPlatformContext: ctx.botPlatformContext,
+ disabledPluginIds: ctx.disabledPluginIds,
discovery,
ephemeralUserMessage: request.ephemeralUserMessage,
globalMemoryEnabled: request.globalMemoryEnabled,
hasMentionedAgents: request.hasMentionedAgents,
loadHistoryMessages: deps.loadHistoryMessages,
mentionedAgents: request.mentionedAgents,
- operationId: request.operationId,
+ operationId,
runAttachments: request.runAttachments,
runFromHistory: request.resumeFromHistory,
selectedSkillIds: request.selectedSkillIds,
@@ -231,7 +239,7 @@ export const runOperationInit = async (
assistantMessageId: ctx.assistantMessageId,
initialContext: prep.initialContext,
messageCount: prep.allMessages.length,
- operationId: request.operationId,
+ operationId,
parentMessageId: request.parentMessageId,
resumeApproval: request.resumeApproval,
resumeApprovalPlugin: request.resumeApprovalPlugin,
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 7b068102360..63e99ec8c4a 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -39,8 +39,19 @@ export interface ExecRunContext {
appContext?: InternalExecAgentParams['appContext'];
/** Persisted assistant placeholder row id (spinner anchor / error sink). */
assistantMessageId: string;
+ /**
+ * Channel facts of a bot-originated run. Ambient like the agent config: the
+ * operation keeps them on `principal.actor.bot` / `world.channel`, so a stage
+ * that re-runs later reads them back from there rather than from the turn's
+ * request.
+ */
+ botContext?: InternalExecAgentParams['botContext'];
+ botPlatformContext?: InternalExecAgentParams['botPlatformContext'];
canUseDevice: boolean;
deviceAccessReason: DeviceAccessReason;
+ /** Tri-state disabled plugin identifiers; mirrored on `world.disabledPluginIds`. */
+ disabledPluginIds: string[];
+ discordContext?: InternalExecAgentParams['discordContext'];
/** Effective model for this run (topic-pinned model already applied). */
model: string;
parentMessageId?: string;
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 12fc57cab89..912605f8fc9 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -13,6 +13,7 @@ import type {
UserMemoryConfig,
} from '@lobechat/context-engine';
import type {
+ AgentRunInitRequest,
AgentShareVisitorContext,
AgentSignalOperationMarker,
ChatToolPayload,
@@ -543,6 +544,20 @@ export interface AgentState {
// --- Principal ---
/** Under whose authority the run acts and what it may do. Frozen at creation. */
principal?: AgentRunPrincipal;
+ /**
+ * The turn's raw ask, kept ONLY while the run still owes its init.
+ *
+ * A run can be created before tool discovery and the context assembly have
+ * happened; the step-0 worker does them and clears this in the same write that
+ * saves what they produced. Its presence is therefore the signal:
+ * a state carrying a request has not been initialized yet.
+ *
+ * Everything else the init needs is already on the other slots (`world.agent`,
+ * `world.channel`, `principal.policy`, `host.hooks`, `modelRuntimeConfig` …) β€”
+ * this is the residue those slots have no claim on.
+ */
+ request?: AgentRunInitRequest;
+
/** @deprecated Use `principal.policy.securityBlacklist`. */
securityBlacklist?: SecurityBlacklistConfig;
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 3f3b0f2292c..17b2ffe552a 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -8,6 +8,7 @@ import type { ComposerUserMessage, TaskDetail, UIChatMessage } from '../message'
import type { ChatTopic } from '../topic';
export * from './credentialFacts';
+export * from './initRequest';
export * from './modelFacts';
/**
diff --git a/packages/types/src/agentExecution/initRequest.ts b/packages/types/src/agentExecution/initRequest.ts
new file mode 100644
index 00000000000..47dbda65b10
--- /dev/null
+++ b/packages/types/src/agentExecution/initRequest.ts
@@ -0,0 +1,96 @@
+import type { ChatAudioItem, ChatFileItem, ChatVideoItem, MessagePluginItem } from '../message';
+import type { RuntimeMentionedAgent } from '../stepContext';
+
+/** Attachments the turn arrived with, already ingested to storage. */
+export interface AgentRunAttachments {
+ audioList?: ChatAudioItem[];
+ fileIds?: string[];
+ fileList?: ChatFileItem[];
+ imageList?: Array<{ alt: string; id: string; url: string }>;
+ videoList?: ChatVideoItem[];
+ /** Per-file ingestion failures; surfaced to the user, never fatal. */
+ warnings: string[];
+}
+
+/** One tool the user approved or rejected in a single action. */
+export interface AgentRunApprovalDecision {
+ decision: 'approved' | 'rejected' | 'rejected_continue';
+ parentMessageId: string;
+ rejectionReason?: string;
+ toolCallId: string;
+}
+
+/**
+ * What the caller asked for on this turn: the prompt's attachments, the tools
+ * they picked, the flags the entry point set, and the human decision a resumed
+ * approval carries.
+ *
+ * Every OTHER fact a run needs already has a typed home: the agent snapshot and
+ * the channel facts on `world`, the approval mode on `principal.policy`, the
+ * hooks and the queue policy on `host`, the model on `modelRuntimeConfig`. This
+ * is the residue β€” the raw ask, which tool discovery and the context assembly
+ * consume and then throw away.
+ *
+ * It lives on the state only while that work is still pending, which is what
+ * lets it happen in the step-0 worker instead of on the send path
+ *. Plain JSON, because the state round-trips through Redis.
+ */
+export interface AgentRunInitRequest {
+ /** Internal additions (e.g. the task tool during task execution). */
+ additionalPluginIds?: string[];
+ agentSlug?: string | null;
+ /** Assistant that emitted the approved batch β€” the pending tool rows' parent. */
+ approvalOwnerAssistantId?: string;
+ /** Approved decisions paired with the tool row each one fills. */
+ approvedToolEntries: { plugin: MessagePluginItem; toolMessageId: string }[];
+ attachedFileIds?: string[];
+ /**
+ * Files whose parsed body was left out of this request because it lives in
+ * the documents table already. A parsed attachment can run to tens of MB β€” far
+ * past what one state write can carry β€” so a persisted request keeps only the
+ * id and the init reads the body back.
+ */
+ detachedFileContentIds?: string[];
+ disableLocalSystem?: boolean;
+ disableSelfFeedbackIntentTool?: boolean;
+ disableTools?: boolean;
+ /** A user turn that is prompted but never persisted (self-iteration runs). */
+ ephemeralUserMessage?: string;
+ /** When set, the run may use ONLY these tools. */
+ exclusivePluginIds?: string[];
+ /** Mime types of the raw bot/IM uploads β€” all discovery reads off them. */
+ externalFileTypes?: string[];
+ /** Response-API client function tools the caller injected. */
+ functionTools?: Array<{ description?: string; name: string; parameters?: Record<string, any> }>;
+ globalMemoryEnabled: boolean;
+ hasMentionedAgents: boolean;
+ /** The caller pinned a device; the run must not silently execute elsewhere. */
+ isFixedDeviceTarget: boolean;
+ localDeviceId?: string;
+ mentionedAgents?: RuntimeMentionedAgent[];
+ parentMessageId?: string;
+ requestedDeviceId?: string;
+ requestTrigger?: string;
+ resumeApproval?: AgentRunApprovalDecision;
+ /** The pending tool row a single approval resumes. */
+ resumeApprovalPlugin?: MessagePluginItem;
+ resumeApprovals?: AgentRunApprovalDecision[];
+ /** The run continues from history instead of a new user turn. */
+ resumeFromHistory: boolean;
+ resumeToolResult?: {
+ content: string;
+ outcome?: 'skipped' | 'submitted';
+ parentMessageId: string;
+ pluginState?: Record<string, unknown>;
+ rejectionReason?: string;
+ toolCallId: string;
+ };
+ runAttachments: AgentRunAttachments;
+ /** Skill identifiers the composer or CLI selected for this message. */
+ selectedSkillIds?: string[];
+ /** Tool identifiers the user @-mentioned in this message. */
+ selectedToolIds?: string[];
+ /** The Task this run executes, when it runs inside the Task system. */
+ taskId?: string;
+ topicBoundDeviceId?: string | null;
+}