π€― 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
β»οΈ refactor(agent): put a run's init behind one serializable request (#19762)
Arvin Xu0ea993656e66
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 407533a99fa..b36f1787879 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -58,16 +58,12 @@ import { createGraphAwareAgentFactory } from './helpers/agentFactory';import { createGroupActionMemberBridgeHook } from './hooks/threadRunHooks';import { InterventionController } from './intervention/InterventionController';import type { ApprovalClaimState } from './pipeline/approvalResume';-import {- buildApprovalResumeContext,- claimApprovalResume,- tryReuseInterventionContinuation,-} from './pipeline/approvalResume';+import { claimApprovalResume, tryReuseInterventionContinuation } from './pipeline/approvalResume';import { dispatchHeteroAgent } from './pipeline/heteroDispatch';-import { createHistoryMessagesLoader, prepareOperation } from './pipeline/operationPrep';+import { buildOperationInitRequest, runOperationInit } from './pipeline/operationInit';+import { createHistoryMessagesLoader } from './pipeline/operationPrep';import { resolveRunAgentConfig } from './pipeline/resolveRunAgentConfig';import { startOperation } from './pipeline/startOperation';-import { discoverTools } from './pipeline/toolDiscovery';import { resolveNewTopicSnapshot, setupTurn } from './pipeline/turnSetup';import { createRunFacts, type RunFacts } from './runFacts';import { applyShareGateToAgentConfig } from './shareGate';@@ -1169,99 +1165,72 @@ export class AiAgentService {// injected separately via `initialContext.mentionedAgents` below.const hasMentionedAgents = !appContext?.groupId && !!mentionedAgents?.length;- // Stage 5 (5aβ5f) β tool discovery (see `pipeline/toolDiscovery`).- const discovery = await discoverTools(+ // 15. Generate operation ID: op_{timestamp}_{agentId}_{topicId}_{random}+ const operationId =+ continuationOperationId ?? `op_${Date.now()}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;++ // Stages 5β18 β the run's init: the tool surface, the message/context+ // assembly, and the human decision a resumed approval turns into the first+ // context. One call so the same work can later run in the step-0 worker+ // instead of on the send path (LOBE-13745).+ const initRequest = buildOperationInitRequest({+ additionalPluginIds,+ agentSlug,+ approvalOwnerAssistantId,+ approvedToolEntries,+ attachedFileIds,+ botContext,+ botPlatformContext,+ disableLocalSystem,+ disableSelfFeedbackIntentTool: params.disableSelfFeedbackIntentTool,+ disableTools: params.disableTools,+ disabledPluginIds,+ discordContext,+ ephemeralUserMessage,+ exclusivePluginIds,+ files,+ functionTools,+ globalMemoryEnabled,+ hasMentionedAgents,+ isFixedDeviceTarget: turn.isFixedDeviceTarget,+ localDeviceId,+ mentionedAgents,+ operationId,+ parentMessageId,+ requestTrigger: requestTriggerMetadata.trigger,+ requestedDeviceId,+ resumeApproval,+ resumeApprovalPlugin,+ resumeApprovals,+ resumeFromHistory: runFromHistory,+ resumeToolResult,+ runAttachments,+ selectedToolIds,+ topicBoundDeviceId: turn.topicBoundDeviceId,+ });++ const { discovery, initialContext, prep } = await runOperationInit({agentDocumentsService: this.agentDocumentsService,+ agentModel: this.agentModel,+ bindTopicWorkingDirectory: (p) => this.bindTopicWorkingDirectory(p),composioService: this.composioService,connectorModel: this.connectorModel,connectorToolModel: this.connectorToolModel,db: this.db,getMarketService: () => this.getMarketService(runFacts),+ loadHistoryMessages,messageModel: this.messageModel,pluginModel: this.pluginModel,- userId: this.userId,- workspaceId: this.workspaceId,- },- runContext,- {- additionalPluginIds,- agentSlug,- attachedFileIds,- botContext,- disableLocalSystem,- disableSelfFeedbackIntentTool: params.disableSelfFeedbackIntentTool,- disableTools: params.disableTools,- disabledPluginIds,- discordContext,- exclusivePluginIds,- files,- functionTools,- globalMemoryEnabled,- hasMentionedAgents,- isFixedDeviceTarget: turn.isFixedDeviceTarget,- loadHistoryMessages,- localDeviceId,- requestTrigger: requestTriggerMetadata.trigger,- requestedDeviceId,- selectedToolIds,throwIfExecutionAborted,- topicBoundDeviceId: turn.topicBoundDeviceId,- },- );-- // 15. Generate operation ID: agt_{timestamp}_{agentId}_{topicId}_{random}- const timestamp = Date.now();- const operationId =- continuationOperationId ?? `op_${timestamp}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;-- // Stages 9.4β18 β device system info, agent-management context, persona- // memory, history + message assembly, the base initial runtime context,- // workspace init, the OperationSkillSet, and the expertise snapshot- // (see `pipeline/operationPrep`).- const prep = await prepareOperation(- {- agentDocumentsService: this.agentDocumentsService,- agentModel: this.agentModel,- bindTopicWorkingDirectory: (p) => this.bindTopicWorkingDirectory(p),- db: this.db,topicModel: this.topicModel,userId: this.userId,workspaceId: this.workspaceId,},runContext,- {- botPlatformContext,- disabledPluginIds,- discovery,- ephemeralUserMessage,- globalMemoryEnabled,- hasMentionedAgents,- loadHistoryMessages,- mentionedAgents,- operationId,- runAttachments,- runFromHistory,- throwIfExecutionAborted,- },+ initRequest,);- // 16b/16c β override the initial context with the human decision- // (see `pipeline/approvalResume`). Pure; no-op on a fresh send.- const initialContext = buildApprovalResumeContext({- approvalOwnerAssistantId,- approvedToolEntries,- assistantMessageId: turn.assistantMessageId,- initialContext: prep.initialContext,- messageCount: prep.allMessages.length,- operationId,- parentMessageId,- resumeApproval,- resumeApprovalPlugin,- resumeApprovals,- resumeToolResult,- });-// 17. Log final operation parameters summarylog('execAgent: creating operation %s with params: model=%s, provider=%s, tools=%d, messages=%d, manifests=%d',diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.tsnew file mode 100644index 00000000000..6641c38902e--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from 'vitest';++import { buildOperationInitRequest, type OperationInitRequest } from '../operationInit';++const fullInput = (): Parameters<typeof buildOperationInitRequest>[0] => ({+ additionalPluginIds: ['lobe-task'],+ agentSlug: 'my-agent',+ approvalOwnerAssistantId: 'msg-assistant',+ // A batch approval resume: the claim pairs each decision with its plugin row+ // and a `createdAt` used only to order the batch.+ approvedToolEntries: [+ {+ createdAt: new Date('2026-09-20T10:00:00.000Z'),+ plugin: {+ apiName: 'runCommand',+ arguments: '{"command":"ls"}',+ identifier: 'lobe-local-system',+ toolCallId: 'call-1',+ type: 'default',+ },+ toolMessageId: 'msg-tool-1',+ },+ ] 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: [+ { content: new ArrayBuffer(8), mimeType: 'image/png', name: 'a.png' },+ { content: new ArrayBuffer(8), name: 'unknown.bin' },+ ] as any,+ functionTools: [{ function: { name: 'client_fn' }, type: 'function' }] as any,+ globalMemoryEnabled: true,+ hasMentionedAgents: true,+ isFixedDeviceTarget: false,+ localDeviceId: 'device-1',+ mentionedAgents: [{ id: 'agt_2', name: 'Fox' }],+ operationId: 'op-1',+ parentMessageId: 'msg-parent',+ requestTrigger: 'chat' as any,+ requestedDeviceId: 'device-2',+ resumeApproval: undefined,+ resumeApprovalPlugin: undefined,+ resumeApprovals: undefined,+ resumeFromHistory: false,+ resumeToolResult: undefined,+ runAttachments: {+ fileIds: ['file-1'],+ imageList: [{ alt: 'image', id: 'file-1', url: 'https://example.com/a.png' }],+ warnings: [],+ },+ selectedToolIds: ['lobe-web-browsing'],+ topicBoundDeviceId: null,+});++describe('buildOperationInitRequest', () => {+ it('reduces the raw uploads to the mime types discovery actually reads', () => {+ const request = buildOperationInitRequest(fullInput());++ expect(request.externalFileTypes).toEqual(['image/png', '']);+ expect('files' in request).toBe(false);+ });++ it('keeps only what the resume context reads from an approved batch entry', () => {+ const request = buildOperationInitRequest(fullInput());++ expect(request.approvedToolEntries).toEqual([+ {+ plugin: {+ apiName: 'runCommand',+ arguments: '{"command":"ls"}',+ identifier: 'lobe-local-system',+ toolCallId: 'call-1',+ type: 'default',+ },+ toolMessageId: 'msg-tool-1',+ },+ ]);+ // The claim's ordering key is a `Date`; JSON would flatten it to a string.+ expect('createdAt' in request.approvedToolEntries[0]).toBe(false);+ });++ // A deferred init (LOBE-13745) has to carry this request on the operation+ // state through Redis, which is JSON. A `Date`, a `Buffer` or a model instance+ // sneaking into the request would survive the send path and silently degrade+ // there, so hold the line here instead.+ it('stays JSON-safe end to end', () => {+ const request = buildOperationInitRequest(fullInput());++ // eslint-disable-next-line unicorn/prefer-structured-clone+ const roundTripped = JSON.parse(JSON.stringify(request)) as OperationInitRequest;++ expect(roundTripped).toEqual(request);+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/approvalResume.ts b/apps/server/src/services/aiAgent/pipeline/approvalResume.tsindex 10fd9b6a41e..299739a5bd5 100644--- a/apps/server/src/services/aiAgent/pipeline/approvalResume.ts+++ b/apps/server/src/services/aiAgent/pipeline/approvalResume.ts@@ -534,9 +534,19 @@ export const tryReuseInterventionContinuation = async (};};+/**+ * What the resume context needs from an approved entry. `createdAt` orders the+ * batch while the claim is being built and is not needed here, so this shape+ * stays JSON-safe β see `OperationInitRequest`.+ */+export type ApprovedToolEntry = Pick<+ ClaimedApprovalResume['approvedToolEntries'][number],+ 'plugin' | 'toolMessageId'+>;+export interface BuildApprovalResumeContextInput {approvalOwnerAssistantId?: string;- approvedToolEntries: ClaimedApprovalResume['approvedToolEntries'];+ approvedToolEntries: ApprovedToolEntry[];assistantMessageId: string;/** The base context built at step 16 β returned unchanged on a fresh send. */initialContext: AgentRuntimeContext;diff --git a/apps/server/src/services/aiAgent/pipeline/operationInit.ts b/apps/server/src/services/aiAgent/pipeline/operationInit.tsnew file mode 100644index 00000000000..09cefc3f212--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/operationInit.ts@@ -0,0 +1,233 @@+import type { LobeChatDatabase } from '@lobechat/database';+import type { RequestTrigger } from '@lobechat/types';++import type { AgentModel } from '@/database/models/agent';+import type { ConnectorModel } from '@/database/models/connector';+import type { ConnectorToolModel } from '@/database/models/connectorTool';+import type { MessageModel } from '@/database/models/message';+import type { PluginModel } from '@/database/models/plugin';+import type { TopicModel } from '@/database/models/topic';+import type { AgentDocumentsService } from '@/server/services/agentDocuments';+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 {+ type OperationPrepDeps,+ type OperationPrepResult,+ prepareOperation,+} from './operationPrep';+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 (LOBE-13745) 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.+ */+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;+ selectedToolIds?: string[];+ topicBoundDeviceId?: string | null;+}++/** The live half: models, services and the two loaders the stages call back into. */+export interface OperationInitDeps {+ agentDocumentsService: AgentDocumentsService;+ agentModel: AgentModel;+ /** Same contract `prepareOperation` calls with β `{ config, currentWorkingDirectory, topicId }`. */+ bindTopicWorkingDirectory: OperationPrepDeps['bindTopicWorkingDirectory'];+ composioService: ComposioService;+ connectorModel: ConnectorModel;+ connectorToolModel: ConnectorToolModel;+ db: LobeChatDatabase;+ getMarketService: () => Promise<MarketService>;+ /** Shared lazy loader β tool discovery probes media availability, prep assembles messages. */+ loadHistoryMessages: () => Promise<any[]>;+ messageModel: MessageModel;+ pluginModel: PluginModel;+ throwIfExecutionAborted: (stage: string) => Promise<void>;+ topicModel: TopicModel;+ userId: string;+ workspaceId?: string;+}++export interface OperationInitResult {+ discovery: ToolDiscoveryResult;+ /** Prep's runtime context with the human approval decision applied. */+ initialContext: OperationPrepResult['initialContext'];+ prep: OperationPrepResult;+}++/**+ * Collect the init stage's serializable inputs in one place, so the caller can+ * hand the same request to a synchronous init or (later) persist it for a+ * deferred one.+ */+export const buildOperationInitRequest = (+ input: Omit<OperationInitRequest, 'approvedToolEntries' | 'externalFileTypes'> & {+ /** The claim's entries, `createdAt` and all β dropped here. */+ approvedToolEntries: ClaimedApprovalResume['approvedToolEntries'];+ files?: InternalExecAgentParams['files'];+ },+): OperationInitRequest => {+ const { approvedToolEntries, files, ...rest } = input;+ return {+ ...rest,+ // Keep only what the resume context reads. The claim orders the batch by+ // `createdAt`, a `Date` that JSON would turn into a string β and this+ // request has to survive that round trip byte for byte.+ approvedToolEntries: approvedToolEntries.map(({ plugin, toolMessageId }) => ({+ plugin,+ toolMessageId,+ })),+ ...(files && { externalFileTypes: files.map((file) => file.mimeType ?? '') }),+ };+};++/**+ * 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+ * approval turns into the first context.+ *+ * Runs on the send path today. It takes `(deps, ctx, request)` rather than+ * reading a service instance so the same call can be made from a step-0 worker+ * that rebuilt `deps` and `ctx` from the request β see LOBE-13745.+ */+export const runOperationInit = async (+ deps: OperationInitDeps,+ ctx: ExecRunContext,+ request: OperationInitRequest,+): Promise<OperationInitResult> => {+ // Stage 5 (5aβ5f) β tool discovery (see `pipeline/toolDiscovery`).+ const discovery = await discoverTools(+ {+ agentDocumentsService: deps.agentDocumentsService,+ composioService: deps.composioService,+ connectorModel: deps.connectorModel,+ connectorToolModel: deps.connectorToolModel,+ db: deps.db,+ getMarketService: deps.getMarketService,+ messageModel: deps.messageModel,+ pluginModel: deps.pluginModel,+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ },+ ctx,+ {+ additionalPluginIds: request.additionalPluginIds,+ agentSlug: request.agentSlug,+ attachedFileIds: request.attachedFileIds,+ botContext: request.botContext,+ disableLocalSystem: request.disableLocalSystem,+ disableSelfFeedbackIntentTool: request.disableSelfFeedbackIntentTool,+ disableTools: request.disableTools,+ disabledPluginIds: request.disabledPluginIds,+ discordContext: request.discordContext,+ exclusivePluginIds: request.exclusivePluginIds,+ externalFileTypes: request.externalFileTypes,+ functionTools: request.functionTools,+ globalMemoryEnabled: request.globalMemoryEnabled,+ hasMentionedAgents: request.hasMentionedAgents,+ isFixedDeviceTarget: request.isFixedDeviceTarget,+ loadHistoryMessages: deps.loadHistoryMessages,+ localDeviceId: request.localDeviceId,+ requestTrigger: request.requestTrigger,+ requestedDeviceId: request.requestedDeviceId,+ selectedToolIds: request.selectedToolIds,+ throwIfExecutionAborted: deps.throwIfExecutionAborted,+ topicBoundDeviceId: request.topicBoundDeviceId,+ },+ );++ // Stages 9.4β18 β device system info, agent-management context, persona+ // memory, history + message assembly, the base initial runtime context,+ // workspace init, the OperationSkillSet, and the expertise snapshot+ // (see `pipeline/operationPrep`).+ const prep = await prepareOperation(+ {+ agentDocumentsService: deps.agentDocumentsService,+ agentModel: deps.agentModel,+ bindTopicWorkingDirectory: deps.bindTopicWorkingDirectory,+ db: deps.db,+ topicModel: deps.topicModel,+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ },+ ctx,+ {+ botPlatformContext: request.botPlatformContext,+ disabledPluginIds: request.disabledPluginIds,+ discovery,+ ephemeralUserMessage: request.ephemeralUserMessage,+ globalMemoryEnabled: request.globalMemoryEnabled,+ hasMentionedAgents: request.hasMentionedAgents,+ loadHistoryMessages: deps.loadHistoryMessages,+ mentionedAgents: request.mentionedAgents,+ operationId: request.operationId,+ runAttachments: request.runAttachments,+ runFromHistory: request.resumeFromHistory,+ throwIfExecutionAborted: deps.throwIfExecutionAborted,+ },+ );++ // 16b/16c β override the initial context with the human decision+ // (see `pipeline/approvalResume`). Pure; no-op on a fresh send.+ const initialContext = buildApprovalResumeContext({+ approvalOwnerAssistantId: request.approvalOwnerAssistantId,+ approvedToolEntries: request.approvedToolEntries,+ assistantMessageId: ctx.assistantMessageId,+ initialContext: prep.initialContext,+ messageCount: prep.allMessages.length,+ operationId: request.operationId,+ parentMessageId: request.parentMessageId,+ resumeApproval: request.resumeApproval,+ resumeApprovalPlugin: request.resumeApprovalPlugin,+ resumeApprovals: request.resumeApprovals,+ resumeToolResult: request.resumeToolResult,+ });++ return { discovery, initialContext, prep };+};diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 2a312a67bb3..bc0e88692b4 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -139,7 +139,12 @@ export interface ToolDiscoveryInput {disableTools?: boolean;discordContext?: any;exclusivePluginIds?: string[];- files?: InternalExecAgentParams['files'];+ /**+ * Mime types of the raw bot/IM uploads. The stage only ever looked at the+ * mime type, and keeping the request JSON-safe is what lets a deferred init+ * carry it on the operation state (LOBE-13745).+ */+ externalFileTypes?: string[];functionTools?: InternalExecAgentParams['functionTools'];globalMemoryEnabled: boolean;hasMentionedAgents: boolean;@@ -277,7 +282,7 @@ export const discoverTools = async (disabledPluginIds,discordContext,exclusivePluginIds,- files,+ externalFileTypes: rawExternalFileTypes,functionTools,globalMemoryEnabled,hasMentionedAgents,@@ -792,7 +797,7 @@ export const discoverTools = async (const modelAbilities =builtinModels.find((item) => item.id === model && item.providerId === provider)?.abilities ??builtinModels.find((item) => item.id === model)?.abilities;- const externalFileTypes = files?.map((file) => file.mimeType ?? '') ?? [];+ const externalFileTypes = rawExternalFileTypes ?? [];const inputFileTypes = [...externalFileTypes, ...(await toolReads.attachedFileTypes)];const inputMediaAvailability = getMediaAvailabilityFromFileTypes(inputFileTypes);let historyMediaAvailability = { hasAudios: false, hasImages: false, hasVideos: false };