π€― 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
β¨ feat(agent): run a deferred init in the step-0 worker (#21586)
Arvin Xu68bcc6b32596
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.tsindex 1a32420202e..a0a2ac3e2a5 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts@@ -1,5 +1,3 @@-import type { AgentState } from '@lobechat/agent-runtime';-import { extractActivatedToolIdsFromMessages, UsageCounter } from '@lobechat/agent-runtime';import debug from 'debug';import {@@ -15,6 +13,11 @@ import {type OperationCreationParams,type OperationCreationResult,} from '../types';+import {+ applyOperationInitSlots,+ buildPreInitState,+ pickOperationInitSlots,+} from './operationInitSlots';import type { AgentRuntimeServiceContext } from './types';import { withoutFrozenModelFacts } from './utils';@@ -44,50 +47,26 @@ export async function createOperation(const {acceptsFileWorks,acceptsMemberRuntimeEnd,- activeDeviceId,- activeDeviceScope,operationId,initialContext,agentConfig,- agentGroup,agentShareVisitor,modelRuntimeConfig,- operationCredentials,userId,autoStart = true,- stream,initialMessages = [],interventionResolution,onInterventionPrepared,appContext,toolSet,hooks,- userInterventionConfig,queueRetries,queueRetryDelay,- searchDecision,- botContext,- botPlatformContext,- deviceAccessPolicy,- connectorOwnershipNote,- discordContext,- evalContext,- evalRuntime,- enableExpertise,- expertise,- projectInstructions,- executionPlan,maxSteps,userMemory,- deviceSystemInfo,- disabledPluginIds,- operationSkillSet,parentOperationId,signal,- userTimezone,- initialLlmCalls = 0,initialStepCount = 0,- workspaceId,} = params;// Persist initial agent_operations row. CompletionLifecycle owns both@@ -198,20 +177,6 @@ export async function createOperation(: 'none',);- // Initialize operation state - create state before saving- const activatableToolIds = new Set(operationToolSet.activatableToolIds ?? []);- const restoredActivatedToolIds = extractActivatedToolIdsFromMessages(initialMessages)?.filter(- (id) => activatableToolIds.has(id),- );- const activatedStepTools = restoredActivatedToolIds?.length- ? restoredActivatedToolIds.map((id) => ({- activatedAtStep: initialStepCount,- id,- manifest: operationToolSet.manifestMap[id],- source: 'discovery' as const,- }))- : undefined;-const llmExecutor = await deps.resolveLlmExecutor(params.llmExecutor, parentOperationId);// A member's pushes reach the supervisor's client, so it renders what// that client declared.@@ -221,137 +186,8 @@ export async function createOperation(? await deps.acceptsFileWorks(parentOperationId): undefined);- const initialState = {- activatedStepTools,- createdAt: new Date().toISOString(),- // Store initialContext for executeSync to use- initialContext,- lastModified: new Date().toISOString(),- // Use the passed initial messages- messages: initialMessages,- // Late-bound execution facts. The device may be unrouted here and get- // bound at a later step boundary (`computeDeviceContext`).- ...((activeDeviceId || deviceSystemInfo) && {- binding: {- device: {- ...(activeDeviceId && { id: activeDeviceId }),- ...(deviceSystemInfo && { systemInfo: deviceSystemInfo }),- },- },- }),- // What the host needs to deliver and retry the run. Hooks are stamped- // right after creation once the dispatcher has serialized them.- host: {- ...(fileWorksAccepted === true && { acceptsFileWorks: true }),- ...(params.clientProtocol === 2 && { clientProtocol: 2 as const }),- ...(params.includeFinalState === true && { includeFinalState: true }),- ...(llmExecutor && { llmExecutor }),- queue: { retries: queueRetries, retryDelay: queueRetryDelay },- },- // Run ledger β everything fixed at creation lives in the typed slots.- metadata: {},- // Where the run came from β frozen from here on. Mirrors the- // agent_operations row so the runtime can hang its output on the right- // conversation node without a lookup.- origin: {- agentId: appContext?.agentId,- continuation: interventionResolution,- defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,- documentId: appContext?.documentId ?? undefined,- editingAgentId: appContext?.editingAgentId,- editingGroupId: appContext?.editingGroupId,- groupId: appContext?.groupId ?? undefined,- lineage: {- isSubAgent: appContext?.isSubAgent,- orchestrationRole: appContext?.orchestrationRole,- parentOperationId,- progressAnchor: appContext?.subAgentProgress,- },- projectId: appContext?.projectId,- scope: appContext?.scope ?? undefined,- sessionId: appContext?.sessionId,- signal: appContext?.agentSignal,- sourceMessageId: appContext?.sourceMessageId,- taskId: appContext?.taskId,- threadId: appContext?.threadId ?? undefined,- topicId: appContext?.topicId ?? undefined,- trigger: appContext?.trigger,- userId,- workspaceId,- },- maxSteps,- // modelRuntimeConfig at state level for executor fallback- modelRuntimeConfig,- // Read once during discovery; dropped again as soon as the run changes- // its own credentials (see the creds invalidation after a step).- operationCredentials,- operationId,- // The run's only copy of its tool set. The manifest map is the heaviest- // thing on the state and the state is re-serialized at every step, so the- // former top-level mirrors (`tools`, `toolManifestMap`, `toolSourceMap`,- // `toolExecutorMap`) are no longer written; readers go through- // `selectToolManifestMap` and friends.- operationToolSet,- status: 'idle',- stepCount: initialStepCount,- llmCalls: initialLlmCalls,- // Compat mirror for a rolling deploy: a worker still running the- // pre-`llmCalls` build reports only `usage.llm.apiCalls`, so a resumed- // run that seeds its prior total here alone would lose every call made- // before the resume the moment one of those workers finalizes it. Seeding- // both keeps `getLlmCallCount`'s max() additive on either build.- ...(initialLlmCalls > 0 && {- usage: UsageCounter.accumulateAttempts(undefined, initialLlmCalls),- }),- // How the run executes β frozen from here on.- plan: {- eval: evalRuntime,- execution: executionPlan,- skills: operationSkillSet,- stream,- workingDirectory: agentConfig?.chatConfig?.runtimeEnv?.workingDirectory,- },- // Under whose authority the run acts and what it may do β decided here,- // re-presented (never re-derived) at each dispatch boundary.- principal: {- actor: {- bot: botContext,- deviceScope: activeDeviceScope,- shareVisitor: agentShareVisitor,- },- audit: { clientIp: appContext?.clientIp, userAgent: appContext?.userAgent },- // What the run may do, decided once here: device access and the- // approval mode its tool calls answer to.- policy: { deviceAccess: deviceAccessPolicy, userIntervention: userInterventionConfig },- },- // Compat mirrors for a rolling deploy: a worker still running the- // pre-slot build reads only these, and a missing approval mode defaults- // to `manual` there β which parks a headless run on an approval nobody- // can give. Drop them (and the matching entries in- // `normalizeAgentState`'s COMPAT_MIRROR_PATHS) once no pre-slot worker- // can pick up a step.- enableExpertise,- expertise,- userInterventionConfig,- // What the model is told about the run's world β frozen from here on;- // the context engine reads it on every step.- world: {- agent: agentConfig,- ...((botPlatformContext || discordContext) && {- channel: { botPlatform: botPlatformContext, discord: discordContext },- }),- connectorOwnershipNote,- disabledPluginIds,- enableExpertise,- eval: evalContext,- expertise,- group: agentGroup,- projectInstructions,- searchDecision,- userMemory,- userTimezone,- },- } as Partial<AgentState>;+ const preInitState = buildPreInitState(params, { fileWorksAccepted, llmExecutor });+ const initialState = applyOperationInitSlots(preInitState, pickOperationInitSlots(params));// Use coordinator to create operation, automatically sends initialization event.// For an in-group broadcast/speak member, mirror its Gateway stream eventsdiff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.tsnew file mode 100644index 00000000000..5adee6b70dc--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.ts@@ -0,0 +1,280 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { extractActivatedToolIdsFromMessages, UsageCounter } from '@lobechat/agent-runtime';++import { type OperationCreationParams } from '../types';++/**+ * What an operation's init produces: the tool surface, the assembled messages+ * and context, and the facts discovery read once for the whole run. Everything+ * else on the state is known before the init runs.+ */+export type OperationInitSlots = Pick<+ OperationCreationParams,+ | 'activeDeviceId'+ | 'activeDeviceScope'+ | 'agentGroup'+ | 'connectorOwnershipNote'+ | 'deviceSystemInfo'+ | 'executionPlan'+ | 'expertise'+ | 'initialContext'+ | 'initialMessages'+ | 'operationCredentials'+ | 'operationSkillSet'+ | 'projectInstructions'+ | 'searchDecision'+ | 'toolSet'+ | 'userMemory'+> & {+ /** The model facts discovery resolved; `model` / `provider` are known before. */+ modelCapabilities: {+ mediaCapabilities?: Record<string, boolean>;+ modelFacts?: unknown;+ };+};++/**+ * The state an operation is created with before its init runs: everything the+ * send path knows on its own. `createOperation` completes it with+ * `applyOperationInitSlots` straight away; a deferred init completes it later.+ */+export const buildPreInitState = (+ params: OperationCreationParams,+ {+ fileWorksAccepted,+ llmExecutor,+ }: {+ /** The client's `file` Works declaration, inherited by a group member. */+ fileWorksAccepted?: boolean;+ llmExecutor?: NonNullable<AgentState['host']>['llmExecutor'];+ },+): Partial<AgentState> => {+ const {+ agentConfig,+ agentShareVisitor,+ appContext,+ botContext,+ botPlatformContext,+ deviceAccessPolicy,+ disabledPluginIds,+ discordContext,+ enableExpertise,+ evalContext,+ evalRuntime,+ initialLlmCalls = 0,+ initialStepCount = 0,+ interventionResolution,+ maxSteps,+ modelRuntimeConfig,+ operationId,+ parentOperationId,+ queueRetries,+ queueRetryDelay,+ stream,+ userId,+ userInterventionConfig,+ userTimezone,+ workspaceId,+ } = params;++ return {+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ // What the host needs to deliver and retry the run. Hooks are stamped+ // right after creation once the dispatcher has serialized them.+ host: {+ ...(fileWorksAccepted === true && { acceptsFileWorks: true }),+ ...(params.clientProtocol === 2 && { clientProtocol: 2 as const }),+ ...(params.includeFinalState === true && { includeFinalState: true }),+ ...(llmExecutor && { llmExecutor }),+ queue: { retries: queueRetries, retryDelay: queueRetryDelay },+ },+ // Run ledger β everything fixed at creation lives in the typed slots.+ metadata: {},+ // Where the run came from β frozen from here on. Mirrors the+ // agent_operations row so the runtime can hang its output on the right+ // conversation node without a lookup.+ origin: {+ agentId: appContext?.agentId,+ assistantMessageId: appContext?.assistantMessageId,+ continuation: interventionResolution,+ defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,+ documentId: appContext?.documentId ?? undefined,+ editingAgentId: appContext?.editingAgentId,+ editingGroupId: appContext?.editingGroupId,+ groupId: appContext?.groupId ?? undefined,+ lineage: {+ isSubAgent: appContext?.isSubAgent,+ orchestrationRole: appContext?.orchestrationRole,+ parentOperationId,+ progressAnchor: appContext?.subAgentProgress,+ },+ projectId: appContext?.projectId,+ scope: appContext?.scope ?? undefined,+ sessionId: appContext?.sessionId,+ signal: appContext?.agentSignal,+ sourceMessageId: appContext?.sourceMessageId,+ taskId: appContext?.taskId,+ threadId: appContext?.threadId ?? undefined,+ topicId: appContext?.topicId ?? undefined,+ trigger: appContext?.trigger,+ userId,+ workspaceId,+ },+ maxSteps,+ // modelRuntimeConfig at state level for executor fallback+ modelRuntimeConfig,+ operationId,+ status: 'idle',+ stepCount: initialStepCount,+ llmCalls: initialLlmCalls,+ // Compat mirror for a rolling deploy: a worker still running the+ // pre-`llmCalls` build reports only `usage.llm.apiCalls`, so a resumed+ // run that seeds its prior total here alone would lose every call made+ // before the resume the moment one of those workers finalizes it. Seeding+ // both keeps `getLlmCallCount`'s max() additive on either build.+ ...(initialLlmCalls > 0 && {+ usage: UsageCounter.accumulateAttempts(undefined, initialLlmCalls),+ }),+ // How the run executes β frozen from here on.+ plan: {+ eval: evalRuntime,+ stream,+ workingDirectory: agentConfig?.chatConfig?.runtimeEnv?.workingDirectory,+ },+ // Under whose authority the run acts and what it may do β decided here,+ // re-presented (never re-derived) at each dispatch boundary.+ principal: {+ actor: {+ bot: botContext,+ shareVisitor: agentShareVisitor,+ },+ audit: { clientIp: appContext?.clientIp, userAgent: appContext?.userAgent },+ // What the run may do, decided once here: device access and the+ // approval mode its tool calls answer to.+ policy: { deviceAccess: deviceAccessPolicy, userIntervention: userInterventionConfig },+ },+ // Compat mirrors for a rolling deploy: a worker still running the+ // pre-slot build reads only these, and a missing approval mode defaults+ // to `manual` there β which parks a headless run on an approval nobody+ // can give. Drop them (and the matching entries in+ // `normalizeAgentState`'s COMPAT_MIRROR_PATHS) once no pre-slot worker+ // can pick up a step. The `expertise` mirror is the init's.+ enableExpertise,+ userInterventionConfig,+ // What the model is told about the run's world β frozen from here on;+ // the context engine reads it on every step.+ world: {+ agent: agentConfig,+ ...((botPlatformContext || discordContext) && {+ channel: { botPlatform: botPlatformContext, discord: discordContext },+ }),+ disabledPluginIds,+ enableExpertise,+ eval: evalContext,+ userTimezone,+ },+ } as Partial<AgentState>;+};++/** The init's half of a fully-specified creation request. */+export const pickOperationInitSlots = (params: OperationCreationParams): OperationInitSlots => ({+ activeDeviceId: params.activeDeviceId,+ activeDeviceScope: params.activeDeviceScope,+ agentGroup: params.agentGroup,+ connectorOwnershipNote: params.connectorOwnershipNote,+ deviceSystemInfo: params.deviceSystemInfo,+ executionPlan: params.executionPlan,+ expertise: params.expertise,+ initialContext: params.initialContext,+ initialMessages: params.initialMessages,+ modelCapabilities: {+ mediaCapabilities: params.modelRuntimeConfig?.mediaCapabilities,+ modelFacts: params.modelRuntimeConfig?.modelFacts,+ },+ operationCredentials: params.operationCredentials,+ operationSkillSet: params.operationSkillSet,+ projectInstructions: params.projectInstructions,+ searchDecision: params.searchDecision,+ toolSet: params.toolSet,+ userMemory: params.userMemory,+});++/**+ * Write what the init produced into the state's slots. The one place that knows+ * which slot each init output lands in: `createOperation` applies it to the+ * state it is creating, and a deferred init applies it to the state the+ * operation was created with β so the two cannot drift apart.+ */+export const applyOperationInitSlots = (+ state: Partial<AgentState>,+ slots: OperationInitSlots,+): Partial<AgentState> => {+ const { toolSet: operationToolSet } = slots;+ const messages = slots.initialMessages ?? [];++ const activatableToolIds = new Set(operationToolSet.activatableToolIds ?? []);+ const restoredActivatedToolIds = extractActivatedToolIdsFromMessages(messages)?.filter((id) =>+ activatableToolIds.has(id),+ );+ const activatedStepTools = restoredActivatedToolIds?.length+ ? restoredActivatedToolIds.map((id) => ({+ activatedAtStep: state.stepCount ?? 0,+ id,+ manifest: operationToolSet.manifestMap[id],+ source: 'discovery' as const,+ }))+ : undefined;++ const { activeDeviceId, deviceSystemInfo } = slots;++ return {+ ...state,+ activatedStepTools,+ // Store initialContext for executeSync to use+ initialContext: slots.initialContext,+ messages,+ // Late-bound execution facts. The device may be unrouted here and get+ // bound at a later step boundary (`computeDeviceContext`).+ ...((activeDeviceId || deviceSystemInfo) && {+ binding: {+ ...state.binding,+ device: {+ ...state.binding?.device,+ ...(activeDeviceId && { id: activeDeviceId }),+ ...(deviceSystemInfo && { systemInfo: deviceSystemInfo }),+ },+ },+ }),+ modelRuntimeConfig: { ...state.modelRuntimeConfig, ...slots.modelCapabilities } as any,+ // Read once during discovery; dropped again as soon as the run changes+ // its own credentials (see the creds invalidation after a step).+ operationCredentials: slots.operationCredentials,+ // The run's only copy of its tool set. The manifest map is the heaviest+ // thing on the state and the state is re-serialized at every step, so the+ // former top-level mirrors (`tools`, `toolManifestMap`, `toolSourceMap`,+ // `toolExecutorMap`) are no longer written; readers go through+ // `selectToolManifestMap` and friends.+ operationToolSet,+ plan: {+ ...state.plan,+ execution: slots.executionPlan,+ skills: slots.operationSkillSet,+ },+ principal: {+ ...state.principal,+ actor: { ...state.principal?.actor, deviceScope: slots.activeDeviceScope },+ },+ // Compat mirror for a rolling deploy, see `createOperation`.+ expertise: slots.expertise,+ world: {+ ...state.world,+ connectorOwnershipNote: slots.connectorOwnershipNote,+ expertise: slots.expertise,+ group: slots.agentGroup,+ projectInstructions: slots.projectInstructions,+ searchDecision: slots.searchDecision,+ userMemory: slots.userMemory,+ },+ } as Partial<AgentState>;+};diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex af882ad998a..67ce7b4419d 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -465,6 +465,8 @@ export interface OperationCreationParams {* read on the completion path to project receipts.*/agentSignal?: AgentSignalOperationMarker;+ /** Assistant row the run streams into, stored on `state.origin.assistantMessageId`. */+ assistantMessageId?: string;/*** Client IP of the originating request. Spread onto `state.principal.audit.clientIp`* so downstream LLM-call metadata can carry it for auditing and spenddiff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.tsnew file mode 100644index 00000000000..bfdc8c6b39d--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts@@ -0,0 +1,394 @@+import type * as ModelBankModule from 'model-bank';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ applyOperationInitSlots,+ buildPreInitState,+ pickOperationInitSlots,+} from '@/server/services/agentRuntime/AgentRuntimeService/operationInitSlots';++import { AiAgentService } from '../index';+import type * as OperationInitModule from '../pipeline/operationInit';+import { runOperationInit } from '../pipeline/operationInit';++// Use vi.hoisted to ensure mock functions are available before vi.mock runs+const {+ mockMessageCreate,+ mockMessageFindById,+ mockMessageQuery,+ mockCreateOperation,+ mockFindShareById,+ mockQueryTree,+ mockTopicFindById,+} = vi.hoisted(() => ({+ mockCreateOperation: vi.fn(),+ mockFindShareById: vi.fn(),+ mockQueryTree: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockMessageFindById: vi.fn(),+ mockMessageQuery: vi.fn(),+ mockTopicFindById: vi.fn(),+}));++vi.mock('@/database/models/agentShare', () => ({+ AgentShareModel: {+ findByShareId: mockFindShareById,+ isRunStillAuthorized: vi.fn().mockResolvedValue(true),+ },+}));++// Pass-through spy: the seam under test is what each path hands the init.+vi.mock('../pipeline/operationInit', async (importOriginal) => {+ const actual = await importOriginal<typeof OperationInitModule>();+ return { ...actual, runOperationInit: vi.fn(actual.runOperationInit) };+});++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return {+ create: mockMessageCreate,+ findById: mockMessageFindById,+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),+ query: mockMessageQuery,+ queryTopicMessageTree: mockQueryTree,+ update: vi.fn().mockResolvedValue({}),+ };+ }),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ queryAgents: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ };+ }),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(function () {+ return {+ query: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return {+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),+ create: vi.fn().mockResolvedValue({ id: 'topic-new' }),+ findById: mockTopicFindById,+ updateMetadata: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));++// Real implementation wraps the create in a `db.transaction(...)` for+// per-visitor cap enforcement β irrelevant to the read-side guard under test+// here, and `mockDb = {}` has no `transaction`. Delegate straight to the+// underlying model methods so a share-gated run in these tests exercises the+// same message-creation call the non-share path does.+vi.mock('../shareVisitorAbuseGuards', () => ({+ // Not exercised by these tests (they all target an existing topic), but+ // stubbed so an accidental new-topic share run doesn't hit `db.transaction`.+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-shared-new' }),+ reserveShareVisitorTurn: vi.fn(function (_params, createParams, id) {+ return mockMessageCreate(createParams, id);+ }),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(function () {+ return {+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ };+ }),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return {+ createOperation: mockCreateOperation,+ };+ }),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(function () {+ return {+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/composio', () => ({+ ComposioService: vi.fn().mockImplementation(function () {+ return {+ getComposioManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(function () {+ return {+ uploadFromUrl: vi.fn(),+ };+ }),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ },+}));++vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true, video: false, vision: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+ };+});++/** A JSON round trip: the state reaches the worker through Redis. */+// eslint-disable-next-line unicorn/prefer-structured-clone -- JSON semantics (dropped `undefined`s) are the point+const throughRedis = <T>(value: T): T => JSON.parse(JSON.stringify(value));++/**+ * Drop what is rebuilt per process, the `undefined`s JSON would drop anyway, and+ * an empty `appContext` β every stage reads it optionally, so `{}` reads as none.+ */+const comparableContext = ({ runFacts: _runFacts, ...ctx }: any) => {+ const json = throughRedis(ctx);+ if (json.appContext && Object.keys(json.appContext).length === 0) delete json.appContext;+ return json;+};++// The deferred init has to see the run exactly as the send path did and write+// exactly what `createOperation` writes. Both halves are driven end to end+// here: the send path runs as usual, then the worker rebuilds the run from the+// state the send path would have created before its init and runs it again.+describe('AiAgentService.runDeferredInit - parity with the send path', () => {+ let service: AiAgentService;+ const mockDb = {} as any;+ const userId = 'test-user-id';+ const rows = new Map<string, any>();++ beforeEach(() => {+ vi.clearAllMocks();+ rows.clear();+ let nextId = 0;+ mockMessageCreate.mockImplementation(async (params: any, id?: string) => {+ const row = { ...params, id: id ?? `msg-${++nextId}` };+ rows.set(row.id, row);+ return row;+ });+ mockMessageFindById.mockImplementation(async (id: string) => rows.get(id));+ mockMessageQuery.mockResolvedValue([+ { content: 'earlier question', id: 'msg-prev-1', role: 'user' },+ { content: 'earlier answer', id: 'msg-prev-2', role: 'assistant' },+ ]);+ mockCreateOperation.mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ });+ mockTopicFindById.mockResolvedValue(undefined);+ mockQueryTree.mockResolvedValue([]);++ service = new AiAgentService(mockDb, userId);+ });++ afterEach(() => {+ vi.mocked(runOperationInit).mockClear();+ });++ const sendThenDefer = async (params: Parameters<AiAgentService['execAgent']>[0]) => {+ await service.execAgent(params);++ expect(runOperationInit).toHaveBeenCalledTimes(1);+ const [, sendCtx, request, operationId] = vi.mocked(runOperationInit).mock.calls[0];+ const created = mockCreateOperation.mock.calls[0][0];+ const preInitState = buildPreInitState(created, {});++ const deferred = await service.runDeferredInit({+ operationId,+ request: throughRedis(request),+ state: throughRedis({ ...preInitState, request }) as any,+ });++ expect(runOperationInit).toHaveBeenCalledTimes(2);+ const [, workerCtx, workerRequest, workerOperationId] =+ vi.mocked(runOperationInit).mock.calls[1];++ return {+ created,+ deferred,+ operationId,+ preInitState,+ request,+ sendCtx,+ workerCtx,+ workerOperationId,+ workerRequest,+ };+ };++ it('rebuilds the run context and writes the same slots for a follow-up turn', async () => {+ const run = await sendThenDefer({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-existing' },+ prompt: 'a follow-up question',+ });++ expect(run.workerOperationId).toBe(run.operationId);+ expect(throughRedis(run.workerRequest)).toEqual(throughRedis(run.request));+ expect(comparableContext(run.workerCtx)).toEqual(comparableContext(run.sendCtx));++ expect(run.deferred.context).toEqual(throughRedis(run.created.initialContext));+ expect(throughRedis(run.deferred.state)).toEqual(+ throughRedis({+ ...applyOperationInitSlots(run.preInitState, pickOperationInitSlots(run.created)),+ request: run.request,+ }),+ );+ });++ it('reads no history for a turn that opened a new topic, as the send path does', async () => {+ const run = await sendThenDefer({ agentId: 'agent-1', prompt: 'a first question' });++ expect(comparableContext(run.workerCtx)).toEqual(comparableContext(run.sendCtx));+ expect(run.deferred.state.messages).toEqual(throughRedis(run.created.initialMessages));+ });++ // A regenerate has no user row of its own and prunes the branch it replaces.+ it('rebuilds a regenerate, which has no user row, and prunes the same branch', async () => {+ rows.set('u1', { content: 'the question', id: 'u1', role: 'user', topicId: 'topic-1' });+ mockMessageQuery.mockResolvedValue([+ { content: 'the question', id: 'u1', role: 'user' },+ { content: 'OLD answer', id: 'a1', parentId: 'u1', role: 'assistant' },+ ]);+ mockQueryTree.mockResolvedValue([+ { id: 'u1', messageGroupId: null, parentId: null },+ { id: 'a1', messageGroupId: null, parentId: 'u1' },+ ]);++ const run = await sendThenDefer({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ parentMessageId: 'u1',+ prompt: 'ignored',+ resume: true,+ });++ expect(run.workerCtx.userMessageId).toBeUndefined();+ expect(comparableContext(run.workerCtx)).toEqual(comparableContext(run.sendCtx));+ expect(run.deferred.state.messages?.map((m: any) => m.id)).toEqual(['u1']);+ expect(run.deferred.state.messages).toEqual(throughRedis(run.created.initialMessages));+ });++ describe('a share visitor run', () => {+ const shareGate = {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ };+ const liveShare = {+ agentId: 'agent-1',+ ownerId: userId,+ shareConfig: shareGate.shareConfig,+ shareId: 'share-1',+ visibility: 'link',+ };++ it('works under the share as it stands, exactly as the send path did', async () => {+ mockFindShareById.mockResolvedValue(liveShare);++ const run = await sendThenDefer({ agentId: 'agent-1', prompt: 'Hello', shareGate });++ expect(mockFindShareById).toHaveBeenCalledWith(mockDb, 'share-1');+ expect(comparableContext(run.workerCtx)).toEqual(comparableContext(run.sendCtx));+ expect(throughRedis(run.deferred.state.operationToolSet)).toEqual(+ throughRedis(run.created.toolSet),+ );+ });++ it.each([+ ['gone', null],+ ['no longer public', { ...liveShare, visibility: 'private' }],+ ['moved to another agent', { ...liveShare, agentId: 'agent-2' }],+ ])('refuses to initialize when the share is %s', async (_label, share) => {+ mockFindShareById.mockResolvedValue(liveShare);+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello', shareGate });+ const [, , request, operationId] = vi.mocked(runOperationInit).mock.calls[0];+ const state = buildPreInitState(mockCreateOperation.mock.calls[0][0], {});++ mockFindShareById.mockResolvedValue(share);++ await expect(+ service.runDeferredInit({+ operationId,+ request: throughRedis(request),+ state: throughRedis({ ...state, request }) as any,+ }),+ ).rejects.toThrow('no longer authorizes this run');+ expect(runOperationInit).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex f441f264c9a..d4ae7914b1e 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -3,6 +3,7 @@ import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';import type { SandboxStorageClaim } from '@lobechat/builtin-tool-cloud-sandbox';import type { LobeChatDatabase } from '@lobechat/database';import type {+ AgentRunInitRequest,AgentSenderMetadata,ExecAgentResult,ExecGroupAgentParams,@@ -13,7 +14,11 @@ import type {ScheduleAgentRunParams,ScheduleAgentRunResult,} from '@lobechat/types';-import { RequestTrigger } from '@lobechat/types';+import {+ agentShareFileAccessScope,+ ordinaryFileAccessScope,+ RequestTrigger,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import { sql } from 'drizzle-orm';@@ -49,6 +54,7 @@ import type {GroupActionMemberBridgeParams,} from '@/server/services/agentRuntime/types';import { ComposioService } from '@/server/services/composio';+import { DocumentService } from '@/server/services/document';import { MarketService } from '@/server/services/market';import type { SteerQueueScope } from '@/server/services/redis/steerQueue';@@ -60,6 +66,7 @@ import { resolveForegroundInterventionConfig } from './foregroundIntervention';import { createGraphAwareAgentFactory } from './helpers/agentFactory';import { InterventionController } from './intervention/InterventionController';import type { ApprovalClaimState } from './pipeline/approvalResume';+import { runDeferredOperationInit } from './pipeline/deferredInit';import { execAgentTurn, type ExecAgentTurnDeps } from './pipeline/execTurn';import {createGroupMemberApprovalDeps,@@ -70,6 +77,7 @@ import { resolveNewThread } from './pipeline/newThread';import { createGroupAgentTopic, type PrecreatedTopicDeps } from './pipeline/precreatedTopic';import { scheduleAgentRun } from './pipeline/scheduleAgentRun';import { runWithTopicStart, type TopicStartDeps } from './pipeline/topicStart';+import { bindTopicWorkingDirectory } from './pipeline/topicWorkingDirectory';import type { RunFacts } from './runFacts';import { resolveAgentSenderFromOperation } from './sourceAttribution';import { startQueuedFollowUp } from './steerQueue';@@ -174,6 +182,7 @@ export class AiAgentService {execVirtualSubAgent: this.execVirtualSubAgent,execGroupMember: this.execGroupMember,injectQueuedFollowUp: this.injectQueuedFollowUp,+ runDeferredInit: this.runDeferredInit,startQueuedFollowUp: this.startQueuedFollowUp,verifyShareRunStillAuthorized: this.verifyShareRunStillAuthorized,},@@ -629,6 +638,45 @@ export class AiAgentService {workspaceId: this.workspaceId,});+ /**+ * `AgentRuntimeDelegate.runDeferredInit` implementation β see+ * `runDeferredOperationInit` in `./pipeline/deferredInit`.+ *+ * Arrow field (not a method) so it stays bound when handed to+ * AgentRuntimeService.+ */+ runDeferredInit = async (params: {+ operationId: string;+ request: AgentRunInitRequest;+ state: AgentState;+ }) =>+ runDeferredOperationInit(+ {+ agentDocumentsService: this.agentDocumentsService,+ agentModel: this.agentModel,+ bindTopicWorkingDirectory: (p) =>+ bindTopicWorkingDirectory({ topicModel: this.topicModel }, p),+ composioService: this.composioService,+ connectorModel: this.connectorModel,+ connectorToolModel: this.connectorToolModel,+ db: this.db,+ getMarketService: (runFacts) => this.getMarketService(runFacts),+ messageModel: this.messageModel,+ pluginModel: this.pluginModel,+ readFileContent: async (fileId, shareGate) =>+ (+ await new DocumentService(this.db, this.userId, this.workspaceId).parseFile(+ fileId,+ shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,+ )+ ).content ?? undefined,+ topicModel: this.topicModel,+ userId: this.userId,+ workspaceId: this.workspaceId,+ },+ params,+ );+/*** `AgentRuntimeDelegate.verifyShareRunStillAuthorized` implementation β see* `AgentShareModel.isRunStillAuthorized`'s JSDoc for what "authorized" meansdiff --git a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts b/apps/server/src/services/aiAgent/pipeline/deferredInit.tsnew file mode 100644index 00000000000..d30a41c3554--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/deferredInit.ts@@ -0,0 +1,220 @@+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import type { AgentRunInitRequest } from '@lobechat/types';+import debug from 'debug';++import { AgentShareModel } from '@/database/models/agentShare';+import type { AgentConfigWithId } from '@/server/services/agent';+import { applyOperationInitSlots } from '@/server/services/agentRuntime/AgentRuntimeService/operationInitSlots';+import type { MarketService } from '@/server/services/market';++import { createRunFacts, type RunFacts } from '../runFacts';+import type { AgentShareGate } from '../shareGate';+import type { ExecRunContext } from '../types';+import { type OperationInitDeps, runOperationInit } from './operationInit';+import { resolveOperationInitSlots } from './operationInitSlots';+import { createHistoryMessagesLoader } from './operationPrep';++const log = debug('lobe-server:ai-agent-service');++export type DeferredOperationInitDeps = Omit<+ OperationInitDeps,+ 'getMarketService' | 'loadHistoryMessages' | 'readFileContent' | 'throwIfExecutionAborted'+> & {+ getMarketService: (runFacts: RunFacts) => Promise<MarketService>;+ /** Parse an attachment's body within what the run may read (`shareGate`, if any). */+ readFileContent: (fileId: string, shareGate?: AgentShareGate) => Promise<string | undefined>;+};++/**+ * The share a visitor run was created under, re-read from its live row: the+ * init works under the share's CURRENT grants, never a snapshot of them β the+ * same rule `createShareRunScope` follows for every visitor turn. Fails closed:+ * a share that is gone, no longer public or no longer this agent's ends the run.+ */+const resolveShareGate = async (+ deps: Pick<DeferredOperationInitDeps, 'db' | 'userId'>,+ shareVisitor: NonNullable<NonNullable<AgentState['principal']>['actor']>['shareVisitor'],+): Promise<AgentShareGate | undefined> => {+ if (!shareVisitor) return undefined;++ const share = await AgentShareModel.findByShareId(deps.db, shareVisitor.shareId);+ if (+ !share ||+ share.agentId !== shareVisitor.agentId ||+ share.ownerId !== deps.userId ||+ share.visibility !== 'link'+ ) {+ throw new Error(`Share ${shareVisitor.shareId} no longer authorizes this run`);+ }++ return {+ agentId: share.agentId,+ shareConfig: share.shareConfig,+ shareId: share.shareId,+ visitorUserId: shareVisitor.visitorUserId,+ };+};++/**+ * The run context the send path held, read back off the state the operation+ * was created with. Every field comes from the slot that already owns it; the+ * request supplies only the turn's raw ask.+ */+const restoreRunContext = async (+ deps: Pick<DeferredOperationInitDeps, 'db' | 'messageModel' | 'userId' | 'workspaceId'>,+ state: AgentState,+ request: AgentRunInitRequest,+): Promise<ExecRunContext> => {+ const origin = state.origin ?? {};+ const { lineage } = origin;+ const agentConfig = state.world?.agent as AgentConfigWithId | undefined;+ const { model, provider } = state.modelRuntimeConfig ?? {};++ if (!agentConfig || !model || !provider || !origin.topicId || !origin.assistantMessageId) {+ throw new Error(+ 'Operation state lacks the agent, model, topic or assistant row a deferred init needs',+ );+ }++ // A user row exists exactly when the turn did not run from history, and the+ // turn's source message is then that row.+ const userMessageId = request.resumeFromHistory ? undefined : origin.sourceMessageId;+ // The row's metadata as persisted β what a later turn reads back from history.+ const userMessageMetadata = userMessageId+ ? ((await deps.messageModel.findById(userMessageId))?.metadata ?? undefined)+ : undefined;+ const channel = state.world?.channel;+ const deviceAccess = state.principal?.policy?.deviceAccess;++ return {+ agentConfig,+ appContext: {+ agentSignal: origin.signal,+ defaultTaskAssigneeAgentId: origin.defaultTaskAssigneeAgentId,+ documentId: origin.documentId,+ editingAgentId: origin.editingAgentId,+ editingGroupId: origin.editingGroupId,+ groupId: origin.groupId,+ isSubAgent: lineage?.isSubAgent,+ orchestrationRole: lineage?.orchestrationRole,+ projectId: origin.projectId,+ scope: origin.scope,+ sessionId: origin.sessionId,+ subAgentProgress: lineage?.progressAnchor,+ threadId: origin.threadId,+ // The caller's own value, not the resolved topic: history is read from+ // it, so a turn that opened a new topic reads none.+ topicId: request.requestedTopicId,+ viewedGoal: request.viewedGoal,+ } as ExecRunContext['appContext'],+ assistantMessageId: origin.assistantMessageId,+ botContext: state.principal?.actor?.bot,+ botPlatformContext: channel?.botPlatform,+ canUseDevice: deviceAccess?.canUseDevice ?? false,+ deviceAccessReason: deviceAccess?.reason as ExecRunContext['deviceAccessReason'],+ disabledPluginIds: state.world?.disabledPluginIds ?? [],+ discordContext: channel?.discord,+ model,+ parentMessageId: request.parentMessageId,+ persistAgentId: origin.agentId ?? agentConfig.id,+ prompt: request.prompt,+ provider,+ // `origin.agentId` names the Agent Signal target when a marker is set; the+ // agent snapshot is always the executing agent's own row.+ resolvedAgentId: agentConfig.id,+ runFacts: createRunFacts({+ db: deps.db,+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ }),+ shareGate: undefined,+ topicId: origin.topicId,+ trigger: origin.trigger,+ userMessageId,+ userMessageMetadata,+ };+};++/**+ * `AgentRuntimeDelegate.runDeferredInit`: run the init an operation was created+ * without, in the step-0 worker. Rebuilds the send path's run context from the+ * state, runs the same `runOperationInit`, and writes what it produced into the+ * same slots `createOperation` would have (`applyOperationInitSlots`).+ */+export const runDeferredOperationInit = async (+ deps: DeferredOperationInitDeps,+ {+ operationId,+ request,+ state,+ }: { operationId: string; request: AgentRunInitRequest; state: AgentState },+): Promise<{ context: AgentRuntimeContext; state: Partial<AgentState> }> => {+ const ctx = await restoreRunContext(deps, state, request);+ ctx.shareGate = await resolveShareGate(deps, state.principal?.actor?.shareVisitor);++ const effectiveResume =+ !!request.resume ||+ !!request.resumeApproval ||+ !!request.resumeApprovals?.length ||+ !!request.resumeToolResult;++ const loadHistoryMessages = createHistoryMessagesLoader(+ {+ db: deps.db,+ isShareVisitorRun: !!ctx.shareGate,+ messageModel: deps.messageModel,+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ },+ {+ appContext: ctx.appContext,+ effectiveResume,+ existingMessageIds: request.existingMessageIds ?? [],+ parentMessageId: request.parentMessageId,+ // Validated on the send path; history only needs to know its role.+ resumeParentMessage:+ effectiveResume && request.parentMessageId+ ? await deps.messageModel.findById(request.parentMessageId)+ : undefined,+ selfMessageIds: new Set(+ [ctx.userMessageId, ctx.assistantMessageId].filter((id): id is string => !!id),+ ),+ },+ );++ const { discovery, initialContext, prep } = await runOperationInit(+ {+ ...deps,+ getMarketService: () => deps.getMarketService(ctx.runFacts),+ loadHistoryMessages,+ readFileContent: (fileId) => deps.readFileContent(fileId, ctx.shareGate),+ // A Stop during the init is settled by the step once the init returns+ // (`runPendingInit`), so the stages need no abort probe of their own.+ throwIfExecutionAborted: async () => {},+ },+ ctx,+ request,+ operationId,+ );++ const slots = await resolveOperationInitSlots({ discovery, initialContext, prep });+ const initialized = applyOperationInitSlots(state, slots);++ // The prep appends the attachment warnings to the bot channel facts in place;+ // the send path writes that object after the init, so this one does too.+ if (ctx.botPlatformContext && initialized.world) {+ initialized.world = {+ ...initialized.world,+ channel: { ...initialized.world.channel, botPlatform: ctx.botPlatformContext },+ };+ }++ log(+ '[%s] deferred init: tools=%d, messages=%d',+ operationId,+ slots.toolSet.tools?.length ?? 0,+ slots.initialMessages?.length ?? 0,+ );++ return { context: initialContext, state: initialized };+};diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.tsindex 5c5b7d72d7a..569ebf37da4 100644--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts@@ -585,6 +585,7 @@ export const execAgentTurn = async (disableTools: params.disableTools,ephemeralUserMessage,exclusivePluginIds,+ existingMessageIds,files,functionTools,globalMemoryEnabled,@@ -593,17 +594,21 @@ export const execAgentTurn = async (localDeviceId,mentionedAgents,parentMessageId,+ prompt,+ requestedTopicId: appContext?.topicId ?? undefined,requestTrigger: requestTriggerMetadata.trigger,requestedDeviceId: turn.requestedDeviceId,resumeApproval,resumeApprovalPlugin,resumeApprovals,+ resume,resumeFromHistory: runFromHistory,resumeToolResult: resolvedToolResult,runAttachments,selectedSkillIds,selectedToolIds,topicBoundDeviceId: turn.topicBoundDeviceId,+ viewedGoal: appContext?.viewedGoal,});const { discovery, initialContext, prep } = await traceSendStage('operation_init', () =>diff --git a/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.tsnew file mode 100644index 00000000000..7f72fb765a8--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts@@ -0,0 +1,65 @@+import type { OperationInitSlots } from '@/server/services/agentRuntime/AgentRuntimeService/operationInitSlots';++import type { OperationPrepResult } from './operationPrep';+import type { ToolDiscoveryResult } from './toolDiscovery';++/**+ * Read the state slots off what the init produced. Shared by the send path,+ * which hands them to `createOperation`, and by a deferred init, which writes+ * them into the state its operation was created with.+ *+ * Awaits the credential listing last, so the read overlaps with whatever ran+ * since discovery started it.+ */+export const resolveOperationInitSlots = async ({+ discovery,+ initialContext,+ prep,+}: {+ discovery: ToolDiscoveryResult;+ initialContext: OperationPrepResult['initialContext'];+ prep: OperationPrepResult;+}): Promise<OperationInitSlots> => {+ const { audio, video, vision } = discovery.modelMediaCapabilities;++ return {+ activeDeviceId: discovery.activeDeviceId,+ activeDeviceScope: discovery.activeDeviceScope,+ agentGroup: discovery.operationAgentGroup,+ // Run context the context engine injects into the system message β+ // carried on the operation like `expertise`, not on the agent config.+ connectorOwnershipNote: discovery.connectorOwnershipNote,+ deviceSystemInfo:+ Object.keys(prep.deviceSystemInfo).length > 0 ? prep.deviceSystemInfo : undefined,+ executionPlan: discovery.executionPlan,+ expertise: prep.expertise,+ initialContext,+ initialMessages: prep.allMessages,+ modelCapabilities: {+ mediaCapabilities: {+ ...(typeof audio === 'boolean' && { audio }),+ ...(typeof video === 'boolean' && { video }),+ ...(typeof vision === 'boolean' && { vision }),+ },+ // Read once during discovery: every LLM attempt of this run resolves its+ // parameters from here, so no step re-reads the bank, the user's model+ // row or the reasoning config β and none of them can change mid-run.+ modelFacts: discovery.modelFacts,+ },+ // Listed once during discovery: every step renders {{CREDS_LIST}} from+ // here instead of asking the Market API again.+ operationCredentials: await discovery.credentialFactsPromise,+ operationSkillSet: prep.operationSkillSet,+ projectInstructions: prep.projectInstructions,+ searchDecision: discovery.searchDecision,+ toolSet: {+ activatableToolIds: prep.activatableToolIds,+ enabledToolIds: discovery.toolsResult.enabledToolIds,+ executorMap: discovery.toolExecutorMap,+ manifestMap: discovery.toolManifestMap,+ sourceMap: discovery.toolSourceMap,+ tools: discovery.tools,+ },+ userMemory: prep.userMemory,+ };+};diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex a0007924cf3..4f092f13403 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -9,6 +9,7 @@ import { isAbortError } from '@/server/services/agentRuntime/abort';import type { ExecRunContext, InternalExecAgentParams } from '../types';import type { ApprovalClaimState } from './approvalResume';+import { resolveOperationInitSlots } from './operationInitSlots';import type { OperationPrepResult } from './operationPrep';import { traceStartStage } from './sendTracing';import type { ToolDiscoveryResult } from './toolDiscovery';@@ -138,7 +139,6 @@ export const startOperation = async (userInterventionConfig,userTimezone,} = input;- const { audio, video, vision } = discovery.modelMediaCapabilities;// A builder topic continued from another surface (scope `main`, an approval// resume) arrives without the group it edits; the group the topic was opened// on stands in, so the run still knows its target.@@ -190,16 +190,19 @@ export const startOperation = async (const inheritedEditingGroupId = approvalSourceOperationId? await deps.agentRuntimeService.getOperationEditingGroupId(approvalSourceOperationId): undefined;+ const { modelCapabilities, ...initSlots } = await resolveOperationInitSlots({+ discovery,+ initialContext,+ prep,+ });const result = await deps.agentRuntimeService.createOperation({+ ...initSlots,acceptsFileWorks: fileWorksAccepted,acceptsMemberRuntimeEnd: memberRuntimeEndAccepted,clientProtocol: input.clientProtocol,includeFinalState: input.includeFinalState,llmExecutor,- activeDeviceId: discovery.activeDeviceId,- activeDeviceScope: discovery.activeDeviceScope,agentConfig,- agentGroup: discovery.operationAgentGroup,agentShareVisitor: shareGate? {agentId: shareGate.agentId,@@ -240,11 +243,7 @@ export const startOperation = async (visitorUserId: shareGate.visitorUserId,}: undefined,- deviceSystemInfo:- Object.keys(prep.deviceSystemInfo).length > 0 ? prep.deviceSystemInfo : undefined,disabledPluginIds,- executionPlan: discovery.executionPlan,- searchDecision: discovery.searchDecision,userTimezone,appContext: {// Background self-iteration runs execute under a builtin slug (so they@@ -254,6 +253,7 @@ export const startOperation = async (// context (state.origin.agentId) targets the reviewed agent; ordinary// runs (no marker) fall back to the resolved executing agent.agentId: appContext?.agentSignal?.agentId ?? resolvedAgentId,+ assistantMessageId,// Propagate the originating request's client IP / user agent into// state.metadata (via the `...appContext` spread in createOperation) so// downstream LLM-call metadata can carry them for auditing and spend@@ -310,16 +310,9 @@ export const startOperation = async (botPlatformContext,deviceAccessPolicy: { canUseDevice, reason: deviceAccessReason },discordContext,- // Run context the context engine injects into the system message β- // carried on the operation like `expertise`, not on the agent config.- connectorOwnershipNote: discovery.connectorOwnershipNote,evalContext,evalRuntime,enableExpertise,- expertise: prep.expertise,- projectInstructions: prep.projectInstructions,- initialContext,- initialMessages: prep.allMessages,initialLlmCalls,initialStepCount,...(providedApprovalResolutionRequestId && approvalSourceOperationId@@ -339,42 +332,16 @@ export const startOperation = async (}: {}),maxSteps,- modelRuntimeConfig: {- mediaCapabilities: {- ...(typeof audio === 'boolean' && { audio }),- ...(typeof video === 'boolean' && { video }),- ...(typeof vision === 'boolean' && { vision }),- },- // Read once during discovery: every LLM attempt of this run resolves its- // parameters from here, so no step re-reads the bank, the user's model- // row or the reasoning config β and none of them can change mid-run.- modelFacts: discovery.modelFacts,- model,- provider,- },+ modelRuntimeConfig: { ...modelCapabilities, model, provider },hooks,- // Listed once during discovery: every step renders {{CREDS_LIST}} from- // here instead of asking the Market API again. Awaited only now, so the- // read overlapped with the operation preparation that ran in between.- operationCredentials: await discovery.credentialFactsPromise,operationId,parentOperationId,signal,queueRetries,queueRetryDelay,stream,- toolSet: {- activatableToolIds: prep.activatableToolIds,- enabledToolIds: discovery.toolsResult.enabledToolIds,- executorMap: discovery.toolExecutorMap,- manifestMap: discovery.toolManifestMap,- sourceMap: discovery.toolSourceMap,- tools: discovery.tools,- },- operationSkillSet: prep.operationSkillSet,userId: deps.userId,userInterventionConfig,- userMemory: prep.userMemory,workspaceId: deps.workspaceId,});approvalClaim.continuationStarted = true;diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex 912605f8fc9..bc3a777ba2b 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -80,6 +80,8 @@ export interface AgentRunOrigin {// --- Conversation node ---/** Effective message owner for this run (the group member when applicable). */agentId?: string;+ /** Assistant row the run streams into: its spinner anchor and error sink. */+ assistantMessageId?: string;/** Set when this run continues a durable human-intervention claim. */continuation?: InterventionContinuation;// --- Trigger ---diff --git a/packages/types/src/agentExecution/initRequest.ts b/packages/types/src/agentExecution/initRequest.tsindex 47dbda65b10..46e5f0b73db 100644--- a/packages/types/src/agentExecution/initRequest.ts+++ b/packages/types/src/agentExecution/initRequest.ts@@ -58,6 +58,8 @@ export interface AgentRunInitRequest {ephemeralUserMessage?: string;/** When set, the run may use ONLY these tools. */exclusivePluginIds?: string[];+ /** The exact messages the caller supplied as history, instead of the topic's. */+ existingMessageIds?: string[];/** Mime types of the raw bot/IM uploads β all discovery reads off them. */externalFileTypes?: string[];/** Response-API client function tools the caller injected. */@@ -69,8 +71,23 @@ export interface AgentRunInitRequest {localDeviceId?: string;mentionedAgents?: RuntimeMentionedAgent[];parentMessageId?: string;+ /**+ * What the user typed this turn. Also the content of the user row when one was+ * persisted, but a run from history has no row and still reads it.+ */+ prompt: string;requestedDeviceId?: string;+ /**+ * The topic the caller addressed, before the turn resolved or created one.+ * History is read from it, so a turn that opened a new topic reads none.+ */+ requestedTopicId?: string;requestTrigger?: string;+ /**+ * The caller re-answers an existing turn (regenerate / continue). Unlike+ * `resumeFromHistory`, a run that only suppresses its user row does not set it.+ */+ resume?: boolean;resumeApproval?: AgentRunApprovalDecision;/** The pending tool row a single approval resumes. */resumeApprovalPlugin?: MessagePluginItem;@@ -93,4 +110,6 @@ export interface AgentRunInitRequest {/** The Task this run executes, when it runs inside the Task system. */taskId?: string;topicBoundDeviceId?: string | null;+ /** The goal the user was viewing when they sent the turn. */+ viewedGoal?: { goalId: string };}