Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🎼 feat: Unify Agent Turn Execution Behind One Immutable Plan (#15296)
Danny Avilaa5fd00cd7ae4
diff --git a/CONTEXT.md b/CONTEXT.mdindex ce2d0afb09..f45bb9f1c1 100644--- a/CONTEXT.md+++ b/CONTEXT.md@@ -1,6 +1,7 @@# Domain language- **Agent run envelope**: the versioned, JSON-safe request contract created after ingress authentication and protocol validation but before agent, provider, tool, or MCP initialization. It carries only the validated protocol payload and the minimum trusted principal identifiers. The execution host rehydrates all runtime state from those identifiers.+- **Agent turn execution plan**: the immutable, request-local decision compiled once after authentication, agent resolution, and tool initialization. It records the trusted turn origin, conversation lineage, pause capability, binding/action context, and the preferred checkpoint, history, or fresh state-loading strategy without executing the model or owning persistence. Checkpoint failure falls back to durable history within the same Agents lifecycle.- **Effective agent selection**: the resolved endpoint and agent identity after an enforced model spec is applied. Authorization and agent loading must consume this same identity before the Agent run envelope is initialized.- **MCP runtime request body**: trusted chat identifiers supplied only while an MCP server handles an agent request. It enables request-scoped header placeholders without retaining user-specific request data on a shared server definition.- **Caller Capability Projection**: the versioned, SDK-owned classification of currently active tools by direct and programmatic callers. Event-driven execution transports this projection as data; LibreChat intersects it with its trusted registry and never recomputes deferred-tool discovery policy or treats the projection as authorization.@@ -13,5 +14,5 @@- **Event actor head**: the private, durable pointer on an event-bound child conversation to its latest committed LangGraph checkpoint, plus one previous checkpoint for safe cleanup. Only a qualifying applied action advances it through compare-and-swap; failed, cancelled, or no-action invocations leave it unchanged. A legacy-path event marks the head for a cold rebuild from durable message history before fork mode can resume. Every applied commit conflict, unverified commit, or post-commit persistence failure is retained in a private reconciliation journal that blocks later actor turns instead of continuing from stale state; an exact marker can be cleared only after its checkpoint is verified authoritative, its history is repaired, or its external action is explicitly compensated.- **Event actor invocation fork**: a delivery-owned checkpoint namespace copied from the event actor head. A warm invocation receives only the new trusted event, then commits its terminal checkpoint when the expected action is observed or deletes the fork otherwise. Pause-capable actors remain on the existing resumable path until forked HITL has an explicit contract.- **Event actor receipt**: the private, terminal proof stored on the authoritative `AgentTriggerDelivery` row for one bound actor invocation. Its unique delivery identity, terminal resolution, exact checkpoint, and bounded action identity provide replay and recovery for the retention window without storing prompts, events, tool arguments, tool output, or conversation history. It does not own the actor checkpoint; the conversation keeps only the actor head and any active unresolved reconciliation until this receipt is durable.-- **Agent event actor mailbox**: the durable delivery-ordering lane for one authenticated source binding. When enabled after a fleet-wide rollout, it keeps later deliveries queued after transport admission until the current child turn records an authoritative terminal handling outcome. It serializes existing coalesced batches and individual events without becoming a second execution controller or actor checkpoint store.+- **Agent event actor mailbox**: the automatic durable delivery-ordering lane for one authenticated source binding. It keeps later deliveries queued after transport admission until the current child turn records an authoritative terminal handling outcome. It serializes existing coalesced batches and individual events without becoming a second execution controller or actor checkpoint store.- **Theme definition**: a versioned, data-only description of LibreChat semantic colors and shared appearance roles, optionally specialized by light or dark mode. The theme module validates and resolves partial definitions against bundled defaults before adapters apply them. A theme definition does not contain arbitrary CSS, application behavior, or alternate feature layouts.diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.jsindex 9332748507..a947d3682c 100644--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js@@ -74,6 +74,37 @@ const mockIsScheduleLive = jest.fn();const mockDeleteAgentCheckpoint = jest.fn();const mockExecuteAgentEventActor = jest.fn();const mockFindAgentEventAppliedAction = jest.fn();+const mockResolveAgentTurnExecutionPlan = jest.fn((input) => {+ let origin = 'user';+ if (input.isSchedule) {+ origin = 'schedule';+ } else if (input.isEvent || input.event) {+ origin = 'event';+ }+ const checkpointCompatible =+ input.event?.binding != null &&+ input.event?.expectedAction != null &&+ input.checkpointerType !== 'memory' &&+ !input.canPause &&+ !input.hasSkillPrimes &&+ !input.hasMemoryContext &&+ !input.expectedActionMayDetach;+ let strategy = 'history';+ if (input.isNewConversation) {+ strategy = 'fresh';+ } else if (checkpointCompatible) {+ strategy = 'checkpoint';+ }+ return {+ origin,+ strategy,+ conversationId: input.conversationId,+ parentMessageId: input.parentMessageId,+ canPause: input.canPause,+ expectedAction: input.event?.expectedAction,+ binding: input.event?.binding,+ };+});/** Faithful stand-in for the graph-context action recorder: first observed* tool end with a name becomes the receipt. Matching fences are unit-tested* against the real implementation in packages/api. */@@ -169,7 +200,6 @@ jest.mock('@librechat/data-schemas', () => ({jest.mock('@librechat/api', () => ({sendEvent: jest.fn(),- isEnabled: (value) => value === true || value === 'true' || value === '1',isScheduleFireRequest: (...args) => mockIsScheduleFireRequest(...args),exemptFromConcurrencyLimiter: (...args) => mockExemptFromConcurrencyLimiter(...args),toPendingSteer: jest.fn((item) => item),@@ -232,6 +262,7 @@ jest.mock('@librechat/api', () => ({executeAgentEventActor: (...args) => mockExecuteAgentEventActor(...args),findAgentEventAppliedAction: (...args) => mockFindAgentEventAppliedAction(...args),createAgentEventActionRecorder: (...args) => mockCreateAgentEventActionRecorder(...args),+ resolveAgentTurnExecutionPlan: (...args) => mockResolveAgentTurnExecutionPlan(...args),isHITLEnabled: (policy) => policy?.enabled === true,agentRequestsAskUserQuestion: (agent) =>agent?.toolDefinitions?.some((tool) => tool?.name === 'ask_user_question') === true,@@ -321,7 +352,6 @@ function nextTick() {describe('ResumableAgentController resume metadata', () => {beforeEach(() => {jest.clearAllMocks();- process.env.ENABLE_AGENT_EVENT_DURABLE_RECEIPTS = 'true';mockMCPContexts = new WeakMap();mockCheckAndIncrementPendingRequest.mockResolvedValue({ allowed: true });mockDecrementPendingRequest.mockResolvedValue(undefined);@@ -3231,6 +3261,16 @@ describe('ResumableAgentController resume metadata', () => {);await flushBackgroundGeneration();+ expect(mockResolveAgentTurnExecutionPlan).toHaveBeenCalledTimes(1);+ expect(mockResolveAgentTurnExecutionPlan).toHaveBeenCalledWith(+ expect.objectContaining({+ conversationId,+ isEvent: false,+ event: undefined,+ }),+ );+ expect(mockExecuteAgentEventActor).not.toHaveBeenCalled();+ expect(mockCreateAgentEventActionRecorder).not.toHaveBeenCalled();expect(mockSaveMessage).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user-123' }),expect.objectContaining({@@ -4042,7 +4082,7 @@ describe('ResumableAgentController resume metadata', () => {},},config: {- endpoints: { agents: { eventDriven: { checkpointForks: true, durableReceipts: true } } },+ endpoints: { agents: {} },},_isAgentTrigger: true,_agentEventBindingId: 'binding-1',@@ -4061,6 +4101,15 @@ describe('ResumableAgentController resume metadata', () => {);await nextTick();+ expect(mockResolveAgentTurnExecutionPlan).toHaveBeenCalledTimes(1);+ expect(mockResolveAgentTurnExecutionPlan).toHaveBeenCalledWith(+ expect.objectContaining({+ conversationId: 'child-conversation',+ isNewConversation: false,+ canPause: false,+ expectedActionMayDetach: false,+ }),+ );expect(mockExecuteAgentEventActor).toHaveBeenCalledWith(expect.objectContaining({conversationId: 'child-conversation',@@ -4137,7 +4186,7 @@ describe('ResumableAgentController resume metadata', () => {},},config: {- endpoints: { agents: { eventDriven: { checkpointForks: true, durableReceipts: true } } },+ endpoints: { agents: {} },},_isAgentTrigger: true,_agentEventBindingId: 'binding-1',@@ -4228,7 +4277,7 @@ describe('ResumableAgentController resume metadata', () => {},},config: {- endpoints: { agents: { eventDriven: { checkpointForks: true, durableReceipts: true } } },+ endpoints: { agents: {} },},_isAgentTrigger: true,_agentEventBindingId: 'binding-1',@@ -4341,7 +4390,7 @@ describe('ResumableAgentController resume metadata', () => {},},config: {- endpoints: { agents: { eventDriven: { checkpointForks: true, durableReceipts: true } } },+ endpoints: { agents: {} },},_isAgentTrigger: true,_agentEventBindingId: 'binding-1',@@ -4396,20 +4445,11 @@ describe('ResumableAgentController resume metadata', () => {});it.each([- [- 'durable-receipt rollout disabled',- { toolDefinitions: [] },- { eventDriven: { checkpointForks: true } },- undefined,- undefined,- false,- ],['tool approval',{ toolDefinitions: [] },{toolApproval: { enabled: true },- eventDriven: { checkpointForks: true, durableReceipts: true },},undefined,undefined,@@ -4417,14 +4457,14 @@ describe('ResumableAgentController resume metadata', () => {['primary ask_user_question',{ toolDefinitions: [{ name: 'ask_user_question' }] },- { eventDriven: { checkpointForks: true, durableReceipts: true } },+ {},undefined,undefined,],['added-agent ask_user_question',{ toolDefinitions: [] },- { eventDriven: { checkpointForks: true, durableReceipts: true } },+ {},new Map([['added-agent', { toolDefinitions: [{ name: 'ask_user_question' }] }]]),undefined,],@@ -4432,7 +4472,6 @@ describe('ResumableAgentController resume metadata', () => {'memory-checkpointer',{ toolDefinitions: [] },{- eventDriven: { checkpointForks: true, durableReceipts: true },checkpointer: { type: 'memory' },},undefined,@@ -4441,35 +4480,34 @@ describe('ResumableAgentController resume metadata', () => {['always-apply skill prime',{ toolDefinitions: [], alwaysApplySkillPrimes: [{ name: 'playbook', body: '# playbook' }] },- { eventDriven: { checkpointForks: true, durableReceipts: true } },+ {},undefined,undefined,],['manual skill prime',{ toolDefinitions: [], manualSkillPrimes: [{ name: 'playbook', body: '# playbook' }] },- { eventDriven: { checkpointForks: true, durableReceipts: true } },+ {},undefined,undefined,],['skills-capable (history-derived re-priming)',{ toolDefinitions: [] },- { eventDriven: { checkpointForks: true, durableReceipts: true } },+ {},undefined,{ primeInvokedSkills: async () => undefined },],['background-capable expected action',{ toolDefinitions: [], backgroundToolNames: ['submit_move_mcp_chess'] },- { eventDriven: { checkpointForks: true, durableReceipts: true } },+ {},undefined,undefined,],])('keeps %s event actors on the existing resumable path',- async (_label, agent, config, agentConfigs, clientOptions, durableReceiptsEnabled = true) => {- process.env.ENABLE_AGENT_EVENT_DURABLE_RECEIPTS = String(durableReceiptsEnabled);+ async (_label, agent, config, agentConfigs, clientOptions) => {mockGenerationJobManager.claimGeneration.mockResolvedValue(wonGenerationClaim({streamId: 'child-conversation',@@ -4602,7 +4640,7 @@ describe('ResumableAgentController resume metadata', () => {},},config: {- endpoints: { agents: { eventDriven: { checkpointForks: true, durableReceipts: true } } },+ endpoints: { agents: {} },},_isAgentTrigger: true,_agentEventBindingId: 'binding-1',@@ -4677,7 +4715,7 @@ describe('ResumableAgentController resume metadata', () => {},},config: {- endpoints: { agents: { eventDriven: { checkpointForks: true, durableReceipts: true } } },+ endpoints: { agents: {} },},_isAgentTrigger: true,_agentEventBindingId: 'binding-1',@@ -4748,7 +4786,7 @@ describe('ResumableAgentController resume metadata', () => {},},config: {- endpoints: { agents: { eventDriven: { checkpointForks: true, durableReceipts: true } } },+ endpoints: { agents: {} },},_isAgentTrigger: true,_agentEventBindingId: 'binding-1',@@ -4830,7 +4868,7 @@ describe('ResumableAgentController resume metadata', () => {},},config: {- endpoints: { agents: { eventDriven: { checkpointForks: true, durableReceipts: true } } },+ endpoints: { agents: {} },},_isAgentTrigger: true,_agentEventBindingId: 'binding-1',diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.jsindex 22091a0203..2cf4807189 100644--- a/api/server/controllers/agents/request.js+++ b/api/server/controllers/agents/request.js@@ -33,9 +33,9 @@ const {executeAgentEventActor,findAgentEventAppliedAction,createAgentEventActionRecorder,- isEnabled,isHITLEnabled,agentRequestsAskUserQuestion,+ resolveAgentTurnExecutionPlan,} = require('@librechat/api');const { disposeClient } = require('~/server/cleanup');const {@@ -1682,6 +1682,59 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit// this job on the same conversationId before acting on it.client.jobCreatedAt = jobCreatedAt;+ const agentsConfig = req.config?.endpoints?.[EModelEndpoint.agents];+ const eventActorAgents = [+ client?.options?.agent,+ ...(client?.agentConfigs?.values?.() ?? []),+ ].filter(Boolean);+ const eventActorMayPause =+ isHITLEnabled(agentsConfig?.toolApproval) ||+ eventActorAgents.some(agentRequestsAskUserQuestion);+ const eventActorHasSkillPrimes =+ client?.options?.primeInvokedSkills != null ||+ (client?.options?.agent?.alwaysApplySkillPrimes?.length ?? 0) > 0 ||+ (client?.options?.agent?.manualSkillPrimes?.length ?? 0) > 0;+ const expectedActionToolName = agentEventDelivery?.expectedAction?.toolName;+ const eventActorActionMayDetach =+ typeof expectedActionToolName === 'string' &&+ eventActorAgents.some((agent) =>+ (agent.backgroundToolNames ?? []).some(+ (name) =>+ name === expectedActionToolName || name.startsWith(`${expectedActionToolName}_mcp_`),+ ),+ );+ const turnExecutionPlan = resolveAgentTurnExecutionPlan({+ conversationId,+ parentMessageId,+ isNewConversation: isNewConvo,+ isSchedule: scheduleId != null,+ isEvent: req._isAgentTrigger === true,+ event:+ agentEventDelivery?.event != null+ ? {+ type: agentEventDelivery.event.type,+ ...(typeof boundEventBindingId === 'string' &&+ boundEventBindingId.length > 0 &&+ req._agentEventBindingParentConversationId != null+ ? {+ binding: {+ bindingId: boundEventBindingId,+ parentConversationId: req._agentEventBindingParentConversationId,+ },+ }+ : {}),+ ...(agentEventDelivery?.expectedAction == null+ ? {}+ : { expectedAction: agentEventDelivery.expectedAction }),+ }+ : undefined,+ canPause: eventActorMayPause,+ checkpointerType: agentsConfig?.checkpointer?.type,+ hasSkillPrimes: eventActorHasSkillPrimes,+ hasMemoryContext: req.config?.memory != null && req.config.memory.disabled !== true,+ expectedActionMayDetach: eventActorActionMayDetach,+ });+// Resolve title timing from the public agents endpoint first, then fall// back to the agent's actual backing provider/custom endpoint.titleTiming = resolveTitleTiming({@@ -1999,86 +2052,29 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit},};- const checkpointForksEnabled =- req.config?.endpoints?.[EModelEndpoint.agents]?.eventDriven?.checkpointForks === true;- /** This is a deployment barrier, not a principal-scoped feature. It is- * populated from the base config before the listener starts; reading- * merged req.config here would let a user/role/tenant override bypass- * the mixed-version rollout fence. */- const durableActorReceiptsEnabled = isEnabled(- process.env.ENABLE_AGENT_EVENT_DURABLE_RECEIPTS,- );- const agentsConfig = req.config?.endpoints?.[EModelEndpoint.agents];- const eventActorAgents = [- client?.options?.agent,- ...(client?.agentConfigs?.values?.() ?? []),- ].filter(Boolean);- const eventActorMayPause =- isHITLEnabled(agentsConfig?.toolApproval) ||- eventActorAgents.some(agentRequestsAskUserQuestion);- /** Skill bodies are spliced or reconstructed into the message list- * ahead of the newest message, and a warm continuation forwards only- * that newest message — a checkpoint-restored actor would keep serving- * the bodies baked in at its last cold start and never observe an- * edited or newly attached skill. That covers request-time primes AND- * history-derived re-priming: `primeInvokedSkills` re-resolves any- * skill the actor previously invoked, so its mere presence (the skills- * capability) keeps the actor on the legacy path, which rebuilds fresh- * bodies every turn. #15235 tracks the context fingerprint that will- * restore warm continuation for skill-bearing actors. */- const eventActorHasSkillPrimes =- client?.options?.primeInvokedSkills != null ||- (client?.options?.agent?.alwaysApplySkillPrimes?.length ?? 0) > 0 ||- (client?.options?.agent?.manualSkillPrimes?.length ?? 0) > 0;- /** A background-opted expected action can detach: dispatch returns a- * launch handle the evidence fences correctly reject, and the later- * completion is provenance-marked as another turn's work — so a fork- * would classify actionless and settle before the external effect- * lands, with no receipt to stop a retry from dispatching it again.- * The name comparison mirrors matchesExpectedAction's MCP suffix. */- const expectedActionToolName = agentEventDelivery?.expectedAction?.toolName;- const eventActorActionMayDetach =- typeof expectedActionToolName === 'string' &&- eventActorAgents.some((agent) =>- (agent.backgroundToolNames ?? []).some(- (name) =>- name === expectedActionToolName ||- name.startsWith(`${expectedActionToolName}_mcp_`),- ),- );- const canUseEventActorFork =- checkpointForksEnabled &&- durableActorReceiptsEnabled &&- agentsConfig?.checkpointer?.type !== 'memory' &&- !eventActorMayPause &&- !eventActorHasSkillPrimes &&- !eventActorActionMayDetach &&- agentEventDelivery?.event != null &&- agentEventDelivery.expectedAction != null &&- typeof eventTaskId === 'string' &&- req._agentEventBindingParentConversationId != null;+ const usesCheckpointStrategy = turnExecutionPlan.strategy === 'checkpoint';/** Authoritative action proof is captured in graph context the moment* the expected tool executes (see the observer tee in initialize.js);* run-step inspection stays only as a fallback, because the run-step* collection is populated asynchronously and can still be empty the* instant sendMessage resolves — misreading an applied invocation as* actionless would discard its fork and strand the actor cold. */- const eventActorActionRecorder = canUseEventActorFork- ? createAgentEventActionRecorder(agentEventDelivery.expectedAction)+ const eventActorActionRecorder = usesCheckpointStrategy+ ? createAgentEventActionRecorder(turnExecutionPlan.expectedAction): undefined;if (eventActorActionRecorder != null) {req._agentEventActionObserver = eventActorActionRecorder.observeToolEnd;}- const sendPromise = canUseEventActorFork+ const sendPromise = usesCheckpointStrategy? executeAgentEventActor({user: userId,...(eventActorTenantId == null ? {} : { tenantId: eventActorTenantId }),conversationId,- bindingId: boundEventBindingId,+ bindingId: turnExecutionPlan.binding.bindingId,invocationId: eventTaskId,event: agentEventDelivery.event,- expectedAction: agentEventDelivery.expectedAction,+ expectedAction: turnExecutionPlan.expectedAction,signal: job.abortController.signal,checkpointer: req.config?.endpoints?.[EModelEndpoint.agents]?.checkpointer,invoke: async (actorContext) => {@@ -2091,7 +2087,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTitreadAppliedAction: () =>eventActorActionRecorder.read() ??findAgentEventAppliedAction(- agentEventDelivery.expectedAction,+ turnExecutionPlan.expectedAction,client?.run?.getRunSteps?.() ?? [],client?.contentParts ?? [],),diff --git a/api/server/routes/agents/openai.js b/api/server/routes/agents/openai.jsindex 92ceee96b3..cf2cbb6e9a 100644--- a/api/server/routes/agents/openai.js+++ b/api/server/routes/agents/openai.js@@ -23,7 +23,6 @@ const {createAgentEventBindingHandlers,createAgentTriggerIngressHandlers,createMessageFilterPii,- isEnabled,} = require('@librechat/api');const {OpenAIChatCompletionController,@@ -56,7 +55,6 @@ const eventBindingHandlers = createAgentEventBindingHandlers({getMessage: db.getMessage,deleteConvos: db.deleteConvos,reserveThread: db.reserveSubagentThread,- enabled: () => isEnabled(process.env.ENABLE_AGENT_EVENT_CHILD_TURNS),});router.use(preAuthTenantMiddleware);diff --git a/api/server/services/Agents/triggers.js b/api/server/services/Agents/triggers.jsindex f7f493a864..02e9411929 100644--- a/api/server/services/Agents/triggers.js+++ b/api/server/services/Agents/triggers.js@@ -3,7 +3,6 @@ const {createAgentEventContinueResolver,createSubagentCompletionWakeupResolver,GenerationJobManager,- isEnabled,} = require('@librechat/api');const methods = require('~/models');@@ -19,7 +18,6 @@ const service = createAgentTriggerService({methods,getGenerationJob: (conversationId) => GenerationJobManager.getJob(conversationId),fallback: completionResolver,- enabled: () => isEnabled(process.env.ENABLE_AGENT_EVENT_CHILD_TURNS),}),});diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex 9092630302..a6ef6bb581 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -1267,9 +1267,7 @@ const initializeClient = async ({? { tenantId: req.user.tenantId }: {}),},- {- completionWakeups: subagentThreadTaskStore.completionWakeupsEnabled === true,- },+ { completionWakeups: true },): undefined;let hasExistingSubagentTask = false;diff --git a/api/server/services/Endpoints/agents/subagentThreadStore.js b/api/server/services/Endpoints/agents/subagentThreadStore.jsindex 6ab0398f61..27620d3b2c 100644--- a/api/server/services/Endpoints/agents/subagentThreadStore.js+++ b/api/server/services/Endpoints/agents/subagentThreadStore.js@@ -1,7 +1,6 @@const {cacheConfig,ioredisClient,- isEnabled,registerShutdownTask,duplicateIoRedisClient,createSubagentThreadTaskStore,@@ -17,7 +16,6 @@ const { enqueueAgentTrigger } = require('../../Agents/triggers');const GENERATION_DRAIN_TIMEOUT_MS = 45_000;const GENERATION_DRAIN_POLL_MS = 100;const completionWakeupHandler = createSubagentCompletionWakeupHandler(enqueueAgentTrigger);-const completionWakeupsEnabled = () => isEnabled(process.env.ENABLE_SUBAGENT_COMPLETION_WAKEUPS);async function cancelUnroutedGeneration({ userId, tenantId, taskId }) {let job = await GenerationJobManager.getJob(taskId);@@ -78,12 +76,7 @@ const subagentThreadTaskStore = createSubagentThreadTaskStore(renewOwnerAdmission: db.renewSubagentAdmission,releaseOwnerAdmission: db.releaseSubagentAdmission,cancelUnroutedTask: cancelUnroutedGeneration,- onTaskPrepared: (registration) => {- if (!completionWakeupsEnabled()) {- return;- }- return completionWakeupHandler(registration);- },+ onTaskPrepared: completionWakeupHandler,},);@@ -149,8 +142,4 @@ async function configureSubagentTaskRouting() {}module.exports = subagentThreadTaskStore;-Object.defineProperty(module.exports, 'completionWakeupsEnabled', {- enumerable: true,- get: completionWakeupsEnabled,-});module.exports.configureSubagentTaskRouting = configureSubagentTaskRouting;diff --git a/api/server/services/Endpoints/agents/subagentThreadStore.spec.js b/api/server/services/Endpoints/agents/subagentThreadStore.spec.jsindex f829c2092c..3883f2ada4 100644--- a/api/server/services/Endpoints/agents/subagentThreadStore.spec.js+++ b/api/server/services/Endpoints/agents/subagentThreadStore.spec.js@@ -10,7 +10,6 @@ const mockCompletionWakeupHandler = jest.fn().mockResolvedValue(undefined);jest.mock('@librechat/api', () => ({cacheConfig: { USE_REDIS: true, REDIS_KEY_PREFIX: 'test:' },ioredisClient: { duplicate: jest.fn() },- isEnabled: jest.fn(() => false),registerShutdownTask: jest.fn(),duplicateIoRedisClient: jest.fn(),createSubagentThreadTaskStore: jest.fn(() => mockTaskStore),@@ -49,7 +48,6 @@ jest.mock('../../Agents/triggers', () => ({const {ioredisClient,- isEnabled,registerShutdownTask,duplicateIoRedisClient,createSubagentThreadTaskStore,@@ -74,18 +72,10 @@ describe('subagent thread Redis lifecycle', () => {expect(taskStoreMethods.getSubagentTaskControlReplay).toBe(db.getSubagentTaskControlReplay);});- it('reads completion wakeup rollout state at task preparation time', async () => {- isEnabled.mockReturnValueOnce(false);+ it('pre-registers completion wakeups for every prepared task', async () => {+ await taskStoreOptions.onTaskPrepared({ taskId: 'task-1' });- await taskStoreOptions.onTaskPrepared({ taskId: 'disabled' });- expect(mockCompletionWakeupHandler).not.toHaveBeenCalled();- isEnabled.mockReturnValueOnce(true);- await taskStoreOptions.onTaskPrepared({ taskId: 'enabled' });- expect(mockCompletionWakeupHandler).toHaveBeenCalledWith({ taskId: 'enabled' });- isEnabled.mockReturnValueOnce(true);- expect(subagentThreadTaskStore.completionWakeupsEnabled).toBe(true);- isEnabled.mockReturnValueOnce(false);- expect(subagentThreadTaskStore.completionWakeupsEnabled).toBe(false);+ expect(mockCompletionWakeupHandler).toHaveBeenCalledWith({ taskId: 'task-1' });});it('registers local task-store quiescence independently of optional Redis setup', () => {diff --git a/librechat.example.yaml b/librechat.example.yamlindex 41ff2f702f..aacd68aa8c 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -566,26 +566,9 @@ endpoints:# # (optional) Limit the workspace scopes users may select. Omit to allow all three.# statefulCodeSessions:# allowedEnvironments: ["user", "agent-user", "conversation"]- # # (optional) Process-wide event-driven agent rollout controls. Deploy support to- # # every API replica before enabling either producer during a subsequent rollout.+ # # (optional) Trusted origin for internal event delivery. By default, LibreChat+ # # uses its own bound listener; override only for an internal TLS/front-door route.# eventDriven:- # childTurns: false- # completionWakeups: false- # # Serialize each authenticated bound actor's event lane through the- # # authoritative terminal child-turn outcome. Enable only after every- # # API replica supports terminal-handling mailbox blockers.- # actorMailbox: false- # # Reuse bound child state through isolated checkpoint forks. Enable only- # # after every API replica supports this lifecycle. Requires the default- # # Mongo checkpointer; it is incompatible with checkpointer.type: memory.- # # The committed head is an ordinary checkpoint under `checkpointer.ttl`,- # # so an actor idle for longer than that TTL rebuilds from message history- # # on its next event. Lowering the TTL below an actor's event interval- # # leaves it correct but never warm. Agents with skill primes also stay- # # on the legacy path for now, so edited skills always reach the actor.- # checkpointForks: false- # # Optional trusted origin for internal trigger delivery. By default, LibreChat- # # uses its own bound listener; override only for an internal TLS/front-door route.# # selfUrl: 'https://librechat.internal'# # "run_in_background" makes Code Interpreter tools eligible by default and enables per-tool MCP opt-in.# # "tool_intents" enables live model-written labels for native tools and opted-in MCP tools.diff --git a/packages/api/src/agents/__tests__/run-codeTools.test.ts b/packages/api/src/agents/__tests__/run-codeTools.test.tsindex b3739e7632..0ab2ee5f46 100644--- a/packages/api/src/agents/__tests__/run-codeTools.test.ts+++ b/packages/api/src/agents/__tests__/run-codeTools.test.ts@@ -79,9 +79,16 @@ function makeAgent(overrides?: Record<string, unknown>) {async function captureRunConfig(agent = makeAgent(),subagentTasks?: SubagentTaskConfig,+): Promise<Record<string, unknown>> {+ return captureAgentsRunConfig([agent], subagentTasks);+}++async function captureAgentsRunConfig(+ agents: Array<ReturnType<typeof makeAgent>>,+ subagentTasks?: SubagentTaskConfig,): Promise<Record<string, unknown>> {await createRun({- agents: [agent] as never,+ agents: agents as never,signal: new AbortController().signal,streaming: true,streamUsage: true,@@ -187,6 +194,7 @@ describe('createRun code-tool eager/session wiring', () => {toolInput: {},toolOutput: JSON.stringify({ background_task_id: 'task-1', status: 'running' }),toolUseId: 'call-1',+ executingAgentId: 'agent_1',},new AbortController().signal,);@@ -194,4 +202,57 @@ describe('createRun code-tool eager/session wiring', () => {'the host will resume you',);});++ it('keeps wakeup guidance off an ephemeral spawning agent in a shared run', async () => {+ const subagentTasks: HostSubagentTaskConfig = {+ store: new InMemorySubagentTaskStore(),+ scopeId: 'owner:mixed-parent-run',+ completionDelivery: SUBAGENT_COMPLETION_DELIVERY,+ };+ const spawningAgent = {+ subagents: { enabled: true, allowSelf: true },+ toolDefinitions: [],+ toolRegistry: new Map(),+ };+ const runConfig = await captureAgentsRunConfig(+ [+ makeAgent({ ...spawningAgent, id: 'agent_durable' }),+ makeAgent({ ...spawningAgent, id: 'openAI__gpt-4o' }),+ ],+ subagentTasks,+ );+ const [durableInput, ephemeralInput] = (+ runConfig.graphConfig as { agents: Array<Record<string, unknown>> }+ ).agents;+ const pollDescription = (input: Record<string, unknown>) =>+ (input.toolDefinitions as Array<{ name: string; description: string }>).find(+ (definition) => definition.name === CHECK_BACKGROUND_TASK_NAME,+ )?.description;++ expect(pollDescription(durableInput)).toContain('automatic completion delivery');+ expect(pollDescription(ephemeralInput)).not.toContain('automatic completion delivery');++ const hooks = runConfig.hooks as HookRegistry;+ const [matcher] = hooks.getMatchers('PostToolUse');+ const hookInput = {+ hook_event_name: 'PostToolUse' as const,+ runId: 'run-1',+ toolName: 'subagent',+ toolInput: {},+ toolOutput: JSON.stringify({ background_task_id: 'task-1', status: 'running' }),+ toolUseId: 'call-1',+ };+ await expect(+ matcher.hooks[0](+ { ...hookInput, executingAgentId: 'openAI__gpt-4o' },+ new AbortController().signal,+ ),+ ).resolves.toEqual({});+ await expect(+ matcher.hooks[0](+ { ...hookInput, executingAgentId: 'agent_durable' },+ new AbortController().signal,+ ),+ ).resolves.toEqual(expect.objectContaining({ updatedOutput: expect.any(String) }));+ });});diff --git a/packages/api/src/agents/background.spec.ts b/packages/api/src/agents/background.spec.tsindex cb73053bcf..2a32182ee0 100644--- a/packages/api/src/agents/background.spec.ts+++ b/packages/api/src/agents/background.spec.ts@@ -1488,6 +1488,7 @@ describe('runCheckBackgroundTask (singleton)', () => {await runCheckBackgroundTask({userId: 'owner',conversationId: 'wakeup-parent',+ agentId: 'agent_parent',args: { background_task_id: started.task.taskId },subagentTasks,}),@@ -1501,6 +1502,7 @@ describe('runCheckBackgroundTask (singleton)', () => {await runCheckBackgroundTask({userId: 'owner',conversationId: 'wakeup-parent',+ agentId: 'agent_parent',args: {},subagentTasks,}),@@ -1508,6 +1510,18 @@ describe('runCheckBackgroundTask (singleton)', () => {expect(listed.message).toBe(SUBAGENT_WAKEUP_GUIDANCE);expect(listed.tasks[0].message).toBeUndefined();+ const ephemeralPoll = JSON.parse(+ await runCheckBackgroundTask({+ userId: 'owner',+ conversationId: 'wakeup-parent',+ agentId: 'openAI__gpt-4o',+ args: { background_task_id: started.task.taskId },+ subagentTasks,+ }),+ );+ expect(ephemeralPoll.status).toBe('running');+ expect(ephemeralPoll.message).toBeUndefined();+store.control(subagentTasks.scopeId, started.task.taskId, { action: 'cancel' });});diff --git a/packages/api/src/agents/background.ts b/packages/api/src/agents/background.tsindex 079ae3ff62..4b1daa511f 100644--- a/packages/api/src/agents/background.ts+++ b/packages/api/src/agents/background.ts@@ -56,7 +56,7 @@ import {warnUnmatchedSelectionNames,synthesizeSelectionToolOptions,} from './selection';-import { SUBAGENT_WAKEUP_GUIDANCE, usesSubagentCompletionWakeups } from './subagentDelivery';+import { SUBAGENT_WAKEUP_GUIDANCE, agentUsesSubagentCompletionWakeups } from './subagentDelivery';import { SubagentTaskOwnerUnavailableError } from './subagentTaskRouting';import { SET_MEMORY_TOOL_NAME, DELETE_MEMORY_TOOL_NAME } from './memory';import { ASK_USER_QUESTION_TOOL_NAME } from './hitl/askUserQuestionTool';@@ -1327,7 +1327,7 @@ export async function runCheckBackgroundTask(params: {: await routedStore.claimTask(subagentTasks.scopeId, taskId, invocationId);const claimed = serializeSubagentClaim(claim,- usesSubagentCompletionWakeups(subagentTasks),+ agentUsesSubagentCompletionWakeups(subagentTasks, params.agentId),);if (claimed != null) {return JSON.stringify(claimed);@@ -1379,7 +1379,10 @@ export async function runCheckBackgroundTask(params: {const tasks = backgroundTaskRegistry.list(userId, conversationId);let subagentTasks: SerializedSubagentTask[] = [];let listWarning: string | undefined;- const completionWakeups = usesSubagentCompletionWakeups(params.subagentTasks);+ const completionWakeups = agentUsesSubagentCompletionWakeups(+ params.subagentTasks,+ params.agentId,+ );if (params.subagentTasks != null) {try {const routedStore = routedSubagentStore(params.subagentTasks.store);diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.tsindex b0220b3848..d7d2d21360 100644--- a/packages/api/src/agents/index.ts+++ b/packages/api/src/agents/index.ts@@ -25,6 +25,7 @@ export * from './memory';export * from './orphans';export * from './migration';export * from './parameters';+export * from './plan';export * from './prewarm';export * from './ptc';export * from './openai';diff --git a/packages/api/src/agents/plan.spec.ts b/packages/api/src/agents/plan.spec.tsnew file mode 100644index 0000000000..4ad4ef2f67--- /dev/null+++ b/packages/api/src/agents/plan.spec.ts@@ -0,0 +1,73 @@+import type { ResolveAgentTurnExecutionPlanInput } from './plan';+import { resolveAgentTurnExecutionPlan } from './plan';++const baseInput = (): ResolveAgentTurnExecutionPlanInput => ({+ conversationId: 'conversation-1',+ parentMessageId: 'message-1',+ isNewConversation: false,+ canPause: false,+ hasSkillPrimes: false,+ hasMemoryContext: false,+ expectedActionMayDetach: false,+});++const boundEvent = () => ({+ type: 'game.turn.ready',+ binding: {+ bindingId: 'binding-1',+ parentConversationId: 'parent-conversation',+ },+ expectedAction: { toolName: 'submit_move' },+});++describe('resolveAgentTurnExecutionPlan', () => {+ it.each([+ ['user', {}, 'user'],+ ['subagent', { isSubagent: true }, 'subagent'],+ ['completion', { event: { type: 'subagent.completion' } }, 'completion'],+ ['schedule', { isSchedule: true }, 'schedule'],+ ['event', { isEvent: true }, 'event'],+ ['resume', { isResume: true }, 'resume'],+ ] as const)('classifies a %s turn from trusted request facts', (_label, overrides, origin) => {+ expect(resolveAgentTurnExecutionPlan({ ...baseInput(), ...overrides }).origin).toBe(origin);+ });++ it('starts fresh only for a new conversation', () => {+ expect(+ resolveAgentTurnExecutionPlan({ ...baseInput(), isNewConversation: true }).strategy,+ ).toBe('fresh');+ });++ it('attempts a checkpoint for a compatible authenticated bound event', () => {+ expect(resolveAgentTurnExecutionPlan({ ...baseInput(), event: boundEvent() })).toEqual({+ origin: 'event',+ strategy: 'checkpoint',+ conversationId: 'conversation-1',+ parentMessageId: 'message-1',+ canPause: false,+ expectedAction: { toolName: 'submit_move' },+ binding: {+ bindingId: 'binding-1',+ parentConversationId: 'parent-conversation',+ },+ });+ });++ it.each([+ ['no binding', { event: { ...boundEvent(), binding: undefined } }],+ ['no expected action', { event: { ...boundEvent(), expectedAction: undefined } }],+ ['memory checkpointer', { event: boundEvent(), checkpointerType: 'memory' }],+ ['pause-capable run', { event: boundEvent(), canPause: true }],+ ['Skill primes', { event: boundEvent(), hasSkillPrimes: true }],+ ['memory context', { event: boundEvent(), hasMemoryContext: true }],+ ['detachable action', { event: boundEvent(), expectedActionMayDetach: true }],+ ] as const)('falls back to history for %s', (_label, overrides) => {+ expect(resolveAgentTurnExecutionPlan({ ...baseInput(), ...overrides }).strategy).toBe(+ 'history',+ );+ });++ it('returns a frozen plan', () => {+ expect(Object.isFrozen(resolveAgentTurnExecutionPlan(baseInput()))).toBe(true);+ });+});diff --git a/packages/api/src/agents/plan.ts b/packages/api/src/agents/plan.tsnew file mode 100644index 0000000000..802e2ea623--- /dev/null+++ b/packages/api/src/agents/plan.ts@@ -0,0 +1,95 @@+import type { TCheckpointerType } from 'librechat-data-provider';+import type { AgentTriggerExpectedAction } from './triggers/types';++export type AgentTurnOrigin = 'user' | 'subagent' | 'completion' | 'schedule' | 'event' | 'resume';++export type AgentTurnContinuationStrategy = 'checkpoint' | 'history' | 'fresh';++export interface AgentTurnBinding {+ bindingId: string;+ parentConversationId: string;+}++export interface AgentTurnExecutionPlan {+ origin: AgentTurnOrigin;+ strategy: AgentTurnContinuationStrategy;+ conversationId: string;+ parentMessageId?: string;+ canPause: boolean;+ expectedAction?: AgentTriggerExpectedAction;+ binding?: AgentTurnBinding;+}++export interface ResolveAgentTurnExecutionPlanInput {+ conversationId: string;+ parentMessageId?: string;+ isNewConversation: boolean;+ isResume?: boolean;+ isSchedule?: boolean;+ isSubagent?: boolean;+ isEvent?: boolean;+ event?: {+ type: string;+ binding?: AgentTurnBinding;+ expectedAction?: AgentTriggerExpectedAction;+ };+ canPause: boolean;+ checkpointerType?: TCheckpointerType;+ hasSkillPrimes: boolean;+ hasMemoryContext: boolean;+ expectedActionMayDetach: boolean;+}++const COMPLETION_EVENT_TYPE = 'subagent.completion';++function resolveOrigin(input: ResolveAgentTurnExecutionPlanInput): AgentTurnOrigin {+ if (input.isResume === true) {+ return 'resume';+ }+ if (input.isSchedule === true) {+ return 'schedule';+ }+ if (input.event?.type === COMPLETION_EVENT_TYPE) {+ return 'completion';+ }+ if (input.isSubagent === true) {+ return 'subagent';+ }+ if (input.isEvent === true || input.event != null) {+ return 'event';+ }+ return 'user';+}++/** Compiles already-loaded turn facts into one immutable state-loading decision. */+export function resolveAgentTurnExecutionPlan(+ input: ResolveAgentTurnExecutionPlanInput,+): AgentTurnExecutionPlan {+ const origin = resolveOrigin(input);+ const binding = input.event?.binding;+ const expectedAction = input.event?.expectedAction;+ const canAttemptCheckpoint =+ binding != null &&+ expectedAction != null &&+ input.checkpointerType !== 'memory' &&+ !input.canPause &&+ !input.hasSkillPrimes &&+ !input.hasMemoryContext &&+ !input.expectedActionMayDetach;+ let strategy: AgentTurnContinuationStrategy = 'history';+ if (input.isNewConversation) {+ strategy = 'fresh';+ } else if (canAttemptCheckpoint) {+ strategy = 'checkpoint';+ }++ return Object.freeze({+ origin,+ strategy,+ conversationId: input.conversationId,+ ...(input.parentMessageId == null ? {} : { parentMessageId: input.parentMessageId }),+ canPause: input.canPause,+ ...(expectedAction == null ? {} : { expectedAction }),+ ...(binding == null ? {} : { binding }),+ });+}diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.tsindex f1b9eeb246..fe7fd3ac60 100644--- a/packages/api/src/agents/run.ts+++ b/packages/api/src/agents/run.ts@@ -57,6 +57,11 @@ import {stripBackgroundFromToolRegistry,stripBackgroundFromToolDefinitions,} from '~/agents/background';+import {+ createSubagentWakeupHandleHook,+ agentUsesSubagentCompletionWakeups,+ usesSubagentCompletionWakeups,+} from '~/agents/subagentDelivery';import {resolveToolApprovalPolicy,healToolApprovalPolicy,@@ -66,10 +71,6 @@ import {ASK_USER_QUESTION_TOOL_NAME,createAskUserQuestionTool,} from '~/agents/hitl/askUserQuestionTool';-import {- createSubagentWakeupHandleHook,- usesSubagentCompletionWakeups,-} from '~/agents/subagentDelivery';import { applyCustomHandoffPromptKeyCompatibility } from '~/agents/handoffPromptKeyCompatibility';import { stripIntentFromToolRegistry, stripIntentFromToolDefinitions } from '~/agents/intent';import { isSteeringSupported, isSteerPreemptSupported } from '~/agents/steering/runtime';@@ -1801,7 +1802,7 @@ export async function createRun({agentInput.toolDefinitions = registerBackgroundTaskTool({toolRegistry: agentInput.toolRegistry,toolDefinitions: agentInput.toolDefinitions,- subagentCompletionWakeups: usesSubagentCompletionWakeups(subagentTasks),+ subagentCompletionWakeups: agentUsesSubagentCompletionWakeups(subagentTasks, agent.id),}).toolDefinitions;}agentInputs.push(agentInput);@@ -1938,7 +1939,11 @@ export async function createRun({hooks = hooks ?? new HookRegistry();hooks.register('PostToolUse', {pattern: String(Constants.SUBAGENT),- hooks: [createSubagentWakeupHandleHook()],+ hooks: [+ createSubagentWakeupHandleHook((agentId) =>+ agentUsesSubagentCompletionWakeups(subagentTasks, agentId),+ ),+ ],internal: true,});}diff --git a/packages/api/src/agents/subagentDelivery.spec.ts b/packages/api/src/agents/subagentDelivery.spec.tsindex e9b5893543..60ba967b56 100644--- a/packages/api/src/agents/subagentDelivery.spec.ts+++ b/packages/api/src/agents/subagentDelivery.spec.ts@@ -3,13 +3,18 @@ import { SUBAGENT_WAKEUP_GUIDANCE, createSubagentWakeupHandleHook } from './subaconst hookSignal = new AbortController().signal;-function input(toolName: string, toolOutput: unknown): PostToolUseHookInput {+function input(+ toolName: string,+ toolOutput: unknown,+ executingAgentId = 'agent_parent',+): PostToolUseHookInput {return {hook_event_name: 'PostToolUse',toolName,toolInput: {},toolOutput,toolUseId: 'call-1',+ executingAgentId,} as PostToolUseHookInput;}@@ -31,8 +36,9 @@ describe('createSubagentWakeupHandleHook', () => {background_task_id: 'task-1',subagent_thread_id: 'thread-1',status: 'running',- message: SUBAGENT_WAKEUP_GUIDANCE,});+ expect(updated.message).toContain('background_task_id "task-1"');+ expect(updated.message).toContain(SUBAGENT_WAKEUP_GUIDANCE);});it('leaves ordinary background tools and terminal subagent results unchanged', async () => {@@ -60,4 +66,17 @@ describe('createSubagentWakeupHandleHook', () => {hook(input('subagent', JSON.stringify({ status: 'running' })), hookSignal),).resolves.toEqual({});});++ it('leaves the handle unchanged when the executing agent cannot receive wakeups', async () => {+ const hook = createSubagentWakeupHandleHook((agentId) => agentId === 'agent_supported');+ const output = JSON.stringify({ background_task_id: 'task-1', status: 'running' });++ await expect(hook(input('subagent', output, 'ephemeral'), hookSignal)).resolves.toEqual({});+ await expect(+ hook({ ...input('subagent', output), executingAgentId: undefined }, hookSignal),+ ).resolves.toEqual({});+ await expect(hook(input('subagent', output, 'agent_supported'), hookSignal)).resolves.toEqual(+ expect.objectContaining({ updatedOutput: expect.any(String) }),+ );+ });});diff --git a/packages/api/src/agents/subagentDelivery.ts b/packages/api/src/agents/subagentDelivery.tsindex c57add3b3d..28fe3f7476 100644--- a/packages/api/src/agents/subagentDelivery.ts+++ b/packages/api/src/agents/subagentDelivery.ts@@ -1,4 +1,5 @@import { Constants } from '@librechat/agents';+import { isEphemeralAgentId } from 'librechat-data-provider';import type { HookCallback, PostToolUseHookOutput, SubagentTaskConfig } from '@librechat/agents';export const SUBAGENT_COMPLETION_DELIVERY = 'wakeup';@@ -20,6 +21,19 @@ export function usesSubagentCompletionWakeups();}+/** Automatic delivery is agent-specific even though the SDK task scope is run-wide. */+export function agentUsesSubagentCompletionWakeups(+ config: SubagentTaskConfig | undefined,+ agentId: string | undefined,+): config is HostSubagentTaskConfig {+ return (+ usesSubagentCompletionWakeups(config) &&+ typeof agentId === 'string' &&+ agentId !== '' &&+ !isEphemeralAgentId(agentId)+ );+}+function parseOutput(output: unknown): Record<string, unknown> | undefined {if (typeof output === 'object' && output !== null && !Array.isArray(output)) {return output as Record<string, unknown>;@@ -38,9 +52,11 @@ function parseOutput(output: unknown): Record<string, unknown> | undefined {}/** Replaces the SDK's legacy poll-first handle with the host's durable delivery contract. */-export function createSubagentWakeupHandleHook(): HookCallback<'PostToolUse'> {+export function createSubagentWakeupHandleHook(+ supportsWakeup: (agentId: string | undefined) => boolean = () => true,+): HookCallback<'PostToolUse'> {return async (input): Promise<PostToolUseHookOutput> => {- if (input.toolName !== String(Constants.SUBAGENT)) {+ if (input.toolName !== String(Constants.SUBAGENT) || !supportsWakeup(input.executingAgentId)) {return {};}const output = parseOutput(input.toolOutput);@@ -51,7 +67,13 @@ export function createSubagentWakeupHandleHook(): HookCallback<'PostToolUse'> {) {return {};}- const updated = { ...output, message: SUBAGENT_WAKEUP_GUIDANCE };+ /** The client recognizes a durable child handle by its exact host-owned shape+ * and by the message repeating the opaque task identity. Preserve that+ * anti-spoofing contract while replacing the legacy poll-first guidance. */+ const updated = {+ ...output,+ message: `Task handle: background_task_id "${output.background_task_id}". ${SUBAGENT_WAKEUP_GUIDANCE}`,+ };return {updatedOutput: typeof input.toolOutput === 'string' ? JSON.stringify(updated) : updated,};diff --git a/packages/api/src/agents/triggers/README.md b/packages/api/src/agents/triggers/README.mdindex eb83d825f4..55e60a9f1b 100644--- a/packages/api/src/agents/triggers/README.md+++ b/packages/api/src/agents/triggers/README.md@@ -122,11 +122,8 @@ Register a direct child agent once under the same Remote Agents API key that wilThe parent must be an ordinary agent conversation, and the target must be enabled in that parentagent's direct `subagents.agent_ids` list (or be an allowed self-spawn). The reserved childconversation is hidden from conversation lists and remains read-only to human chat routes.-`endpoints.agents.eventDriven.childTurns` defaults to false; enable it only after every API replica-runs a release that understands bound child continuations, otherwise an older worker could-permanently reject a new envelope during a rolling deployment. The legacy-`ENABLE_AGENT_EVENT_CHILD_TURNS` environment variable remains a compatibility fallback.-`AGENT_TRIGGERS_SELF_URL` likewise remains a compatibility fallback for+Bound child continuations are automatic after authentication and binding authorization.+`AGENT_TRIGGERS_SELF_URL` remains a compatibility fallback for`endpoints.agents.eventDriven.selfUrl`; most deployments should omit both and use the boundlistener.@@ -173,25 +170,18 @@ immediately before dispatch, so queued events do not persist stale chat topologyis its default ordering lane. A short-lived internal trigger token plus a second binding lookup isrequired to pass the child-thread write guard; possessing a binding id alone grants no access.-Set `endpoints.agents.eventDriven.actorMailbox: true` only after every API replica runs a release-that understands terminal-handling mailbox blockers. The flag defaults to false for rolling-deployment safety, and `ENABLE_AGENT_EVENT_ACTOR_MAILBOX` remains a compatibility fallback. Once-enabled, a bound actor's next delivery stays queued after the current delivery reaches transport-success and does not dispatch until that child generation records `applied`,+The actor mailbox is automatic for bound continuations. A bound actor's next delivery stays queued+after the current delivery reaches transport success and does not dispatch until that child+generation records `applied`,`completed_no_action`, `failed`, or `cancelled`. Different bindings remain independent and can runin parallel. Existing coalesced batches occupy one mailbox position and retain each member'sindividual receipt. An active mailbox record does not receive its normal success TTL; the 90-dayretention window begins only after terminal handling is recorded.-Set `endpoints.agents.eventDriven.durableReceipts: true` only after every API replica runs the-token-fenced delivery receipt implementation and all pre-upgrade bound-actor deliveries have-drained. It defaults to false so a rolling deployment cannot overlap token-unaware admission-release with a newer token-owned action. Keep it false during the binary rollout, then enable it-deployment-wide together with `checkpointForks` after the old workers and their deliveries are-gone. LibreChat projects this base-only setting into-`ENABLE_AGENT_EVENT_DURABLE_RECEIPTS` before accepting requests; the controller deliberately does-not read the merged per-principal config, so tenant, role, and user overrides cannot bypass the-barrier.+Durable receipts and token-fenced action admission are automatic for bound events with an expected+action. Checkpoint continuation is attempted only when the initialized turn is compatible. A+missing or unrestorable checkpoint falls back to durable message history without weakening the+receipt, authorization, or expected-action fences.### Coalescing observational child events@@ -199,11 +189,6 @@ Sources that can prove several bound `continue` events are interchangeable obserthose deliveries into one bounded child turn. Add the same source-defined compatibility key to eachcompatible request:-Set `endpoints.agents.eventDriven.coalescing: true` only after every API replica runs a release-that understands batched deliveries. It defaults to false so a rolling deployment cannot let an-older worker consume only the root event while silently acknowledging the remaining members. The-`ENABLE_AGENT_EVENT_COALESCING` environment override remains available for compatibility.-```json{"mode": "continue",diff --git a/packages/api/src/agents/triggers/bindingResolver.spec.ts b/packages/api/src/agents/triggers/bindingResolver.spec.tsindex a98773ec4e..9e21bd1bfe 100644--- a/packages/api/src/agents/triggers/bindingResolver.spec.ts+++ b/packages/api/src/agents/triggers/bindingResolver.spec.ts@@ -31,25 +31,6 @@ function envelope(): AgentContinueTriggerEnvelope {}describe('agent event continuation resolver', () => {- it('defers without consuming attempts while the rollout gate is disabled', async () => {- const resolver = createAgentEventContinueResolver({- enabled: () => false,- methods: {- getAgentEventBinding: jest.fn(),- getConvo: jest.fn(),- getMessages: jest.fn(),- } as never,- });-- await expect(- resolver(envelope(), { idempotencyKey: 'trigger-1' } as never),- ).rejects.toMatchObject({- code: 'EVENT_BINDING_DISABLED',- retryable: true,- deferWithoutAttempt: true,- });- });-it('re-resolves the latest assistant leaf immediately before dispatch', async () => {const getMessages = jest.fn(async () => [Object.assign(new AIMessage('done'), {@@ -59,7 +40,6 @@ describe('agent event continuation resolver', () => {}),]) as never;const resolver = createAgentEventContinueResolver({- enabled: () => true,methods: {getAgentEventBinding: jest.fn(async () => ({conversationId: 'child-thread',@@ -97,7 +77,6 @@ describe('agent event continuation resolver', () => {it('fails closed when the durable binding target changed', async () => {const resolver = createAgentEventContinueResolver({- enabled: () => true,methods: {getAgentEventBinding: jest.fn(async () => ({conversationId: 'another-thread',@@ -117,7 +96,6 @@ describe('agent event continuation resolver', () => {it('defers an event while the actor has an active generation', async () => {const resolver = createAgentEventContinueResolver({- enabled: () => true,getGenerationJob: jest.fn(async () => ({ status: 'running' })),methods: {getAgentEventBinding: jest.fn(async () => ({@@ -153,7 +131,6 @@ describe('agent event continuation resolver', () => {it('fails closed after the binding parent is removed', async () => {const resolver = createAgentEventContinueResolver({- enabled: () => true,methods: {getAgentEventBinding: jest.fn(async () => ({conversationId: 'child-thread',@@ -185,7 +162,6 @@ describe('agent event continuation resolver', () => {} as never,}));const resolver = createAgentEventContinueResolver({- enabled: () => true,methods: {getAgentEventBinding,getConvo: jest.fn(),diff --git a/packages/api/src/agents/triggers/bindingResolver.ts b/packages/api/src/agents/triggers/bindingResolver.tsindex 92d4274867..02c9e26483 100644--- a/packages/api/src/agents/triggers/bindingResolver.ts+++ b/packages/api/src/agents/triggers/bindingResolver.ts@@ -20,7 +20,6 @@ export interface AgentEventContinueResolverDeps {| undefined>;fallback?: ContinueResolver;- enabled?: () => boolean;}function invalidBinding(message: string, retryable = false): AgentTriggerExecutionError {@@ -38,7 +37,6 @@ export function createAgentEventContinueResolver({methods,getGenerationJob,fallback,- enabled,}: AgentEventContinueResolverDeps): ContinueResolver {return async (envelope: AgentContinueTriggerEnvelope,@@ -48,20 +46,6 @@ export function createAgentEventContinueResolver({if (bindingId == null || sourceKeyId == null) {return fallback?.(envelope, context);}- if (enabled?.() !== true) {- throw new AgentTriggerExecutionError(- 'Event-driven child turns are disabled on this worker.',- {- mode: 'continue',- certainty: 'definite',- retryable: true,- deferWithoutAttempt: true,- code: 'EVENT_BINDING_DISABLED',- status: 503,- },- );- }-let binding;let latestAssistant;try {diff --git a/packages/api/src/agents/triggers/bindings.spec.ts b/packages/api/src/agents/triggers/bindings.spec.tsindex ff465ab159..c20dfcf5cd 100644--- a/packages/api/src/agents/triggers/bindings.spec.ts+++ b/packages/api/src/agents/triggers/bindings.spec.ts@@ -46,7 +46,6 @@ function dependencies() {})),deleteConvos: jest.fn(async () => ({ deletedCount: 1 })),reserveThread,- enabled: () => true,};}@@ -69,25 +68,6 @@ function app(deps = dependencies()) {}describe('agent event bindings', () => {- it('keeps registration off until every API replica supports child turns', async () => {- const deps = dependencies();- deps.enabled = () => false;- const { server } = app(deps);- const response = await request(server)- .post('/bindings')- .set('Idempotency-Key', 'disabled-binding')- .send({- actorId: 'player-a',- parentConversationId: PARENT_ID,- parentMessageId: PARENT_MESSAGE_ID,- target: { agentId: CHILD_AGENT_ID },- });-- expect(response.status).toBe(503);- expect(response.body.error.code).toBe('event_binding_unavailable');- expect(deps.reserveThread).not.toHaveBeenCalled();- });-it('reserves a hidden depth-one actor thread bound to the authenticated API key', async () => {const { server, deps } = app();const response = await request(server)diff --git a/packages/api/src/agents/triggers/bindings.ts b/packages/api/src/agents/triggers/bindings.tsindex 1cec1d2f30..825d98dd42 100644--- a/packages/api/src/agents/triggers/bindings.ts+++ b/packages/api/src/agents/triggers/bindings.ts@@ -43,7 +43,6 @@ export interface AgentEventBindingDependencies {getMessage: MessageMethods['getMessage'];deleteConvos: ConversationMethods['deleteConvos'];reserveThread: ConversationMethods['reserveSubagentThread'];- enabled?: () => boolean;}class AgentEventBindingError extends Error {@@ -201,16 +200,6 @@ function sendError(res: Response, error: unknown): void {throw error;}-function requireEnabled(deps: AgentEventBindingDependencies): void {- if (deps.enabled?.() !== true) {- throw new AgentEventBindingError(- 'Event-driven child turns are not enabled on this deployment',- 503,- 'event_binding_unavailable',- );- }-}-export function createAgentEventBindingHandlers(deps: AgentEventBindingDependencies): {register: RequestHandler;resolve: RequestHandler;@@ -218,7 +207,6 @@ export function createAgentEventBindingHandlers(deps: AgentEventBindingDependencconst register: RequestHandler = async (baseReq, res, next) => {const req = baseReq as EventBindingRequest;try {- requireEnabled(deps);const principal = requirePrincipal(req);const body = (req.body ?? {}) as RegisterBindingBody;const actorId = requireString(body.actorId, 'actorId', MAX_ACTOR_ID_LENGTH);@@ -417,7 +405,6 @@ export function createAgentEventBindingHandlers(deps: AgentEventBindingDependencnext();return;}- requireEnabled(deps);const id = requireString(body.bindingId, 'bindingId');if (!BINDING_ID_PATTERN.test(id)) {throw new AgentEventBindingError('bindingId is invalid');diff --git a/packages/api/src/agents/triggers/delivery.integration.spec.ts b/packages/api/src/agents/triggers/delivery.integration.spec.tsindex acc09d031f..bc78de4fa1 100644--- a/packages/api/src/agents/triggers/delivery.integration.spec.ts+++ b/packages/api/src/agents/triggers/delivery.integration.spec.ts@@ -140,7 +140,6 @@ describe('durable trigger delivery integration', () => {service = createAgentTriggerService({methods: createMethods(mongoose) as ReturnType<typeof createMethods> &AgentTriggerDeliveryPersistence,- coalescingEnabled: () => true,fetch: fetcher,mintToken: () => 'trigger-token',deliveryOptions: { concurrency: 4, tickMs: 5, retryBaseMs: 5 },diff --git a/packages/api/src/agents/triggers/ingress.spec.ts b/packages/api/src/agents/triggers/ingress.spec.tsindex fcb26753d4..ecda180e97 100644--- a/packages/api/src/agents/triggers/ingress.spec.ts+++ b/packages/api/src/agents/triggers/ingress.spec.ts@@ -51,7 +51,6 @@ function dependencies(getDeliveryStatus: jest.fn(async () => delivery()),now: () => 1_755_430_000_000,createRequestId: () => 'generated-request-id',- coalescingEnabled: () => true,...overrides,};}@@ -231,30 +230,6 @@ describe('agent trigger event ingress', () => {});});- it('rejects coalescing until every API worker has the rollout capability', async () => {- const deps = dependencies({ coalescingEnabled: () => false });- const response = await request(createApp(deps, undefined, true))- .post('/api/agents/v1/events')- .set('Idempotency-Key', 'commentary-disabled-1')- .send({- mode: 'continue',- event: fireEvent().event,- target: {- agentId: 'commentator',- conversationId: 'commentator-thread',- parentMessageId: 'placeholder',- bindingId: `evtbind_${'b'.repeat(48)}`,- sourceKeyId: API_KEY_ID,- },- input: 'Comment on this game start.',- coalesce: { key: 'championship-commentary' },- });-- expect(response.status).toBe(400);- expect(response.body.error.code).toBe('invalid_event');- expect(deps.enqueue).not.toHaveBeenCalled();- });-it('fails closed when the idempotency header is absent or duplicated', async () => {const deps = dependencies();const app = createApp(deps);diff --git a/packages/api/src/agents/triggers/ingress.ts b/packages/api/src/agents/triggers/ingress.tsindex e09a02217d..73cb5f35ee 100644--- a/packages/api/src/agents/triggers/ingress.ts+++ b/packages/api/src/agents/triggers/ingress.ts@@ -14,7 +14,6 @@ import type { AgentTriggerService } from './service';import { AgentTriggerEnvelopeError, createAgentTriggerEnvelope } from './envelope';import { AgentTriggerServiceUnavailableError } from './service';import { AgentTriggerDeliveryError } from './delivery';-import { isEnabled } from '../../utils/common';const IDEMPOTENCY_HEADER = 'idempotency-key';const MAX_IDEMPOTENCY_KEY_LENGTH = 256;@@ -49,7 +48,6 @@ export interface AgentTriggerIngressDependencies {getDeliveryStatus: AgentTriggerService['getDeliveryStatus'];now?: () => number;createRequestId?: () => string;- coalescingEnabled?: () => boolean;}class AgentTriggerIngressError extends TypeError {@@ -134,18 +132,12 @@ function requireBody(value: object | null | undefined): AgentTriggerIngressBodyreturn value as AgentTriggerIngressBody;}-function enqueueOptions(- body: AgentTriggerIngressBody,- coalescingEnabled: boolean,-): AgentTriggerEnqueueOptions {+function enqueueOptions(body: AgentTriggerIngressBody): AgentTriggerEnqueueOptions {if (body.orderingKey != null && typeof body.orderingKey !== 'string') {throw new AgentTriggerIngressError('orderingKey must be a string');}let coalesce: AgentTriggerEnqueueOptions['coalesce'];if (body.coalesce != null) {- if (!coalescingEnabled) {- throw new AgentTriggerIngressError('Agent event coalescing is not enabled on this server');- }if (typeof body.coalesce !== 'object' || Array.isArray(body.coalesce)) {throw new AgentTriggerIngressError('coalesce must be an object');}@@ -225,8 +217,6 @@ export function createAgentTriggerIngressHandlers(deps: AgentTriggerIngressDepen} {const now = deps.now ?? Date.now;const createRequestId = deps.createRequestId ?? randomUUID;- const coalescingEnabled =- deps.coalescingEnabled ?? (() => isEnabled(process.env.ENABLE_AGENT_EVENT_COALESCING));const enqueueEvent: RequestHandler = async (baseReq, res) => {const req = baseReq as AgentTriggerIngressRequest;@@ -279,7 +269,7 @@ export function createAgentTriggerIngressHandlers(deps: AgentTriggerIngressDepentarget: body.target as AgentSteerTarget,});}- const receipt = await deps.enqueue(envelope, enqueueOptions(body, coalescingEnabled()));+ const receipt = await deps.enqueue(envelope, enqueueOptions(body));logger.info('[agent-trigger-ingress] delivery accepted', {delivery_key: receipt.deliveryKey,diff --git a/packages/api/src/agents/triggers/service.delivery.spec.ts b/packages/api/src/agents/triggers/service.delivery.spec.tsindex ff1ecd8e78..22e5bf57a2 100644--- a/packages/api/src/agents/triggers/service.delivery.spec.ts+++ b/packages/api/src/agents/triggers/service.delivery.spec.ts@@ -142,24 +142,6 @@ describe('durable agent trigger service', () => {await service.stop();});- it('rejects coalesced work before persistence unless every worker has the capability', async () => {- const methods = deliveryMethods();- const service = createAgentTriggerService({- methods,- coalescingEnabled: () => false,- deliveryOptions: { concurrency: 1, tickMs: 60_000 },- });- await service.initialize({- address: { address: '127.0.0.1', family: 'IPv4', port: 3080 },- });-- await expect(- service.enqueue(envelope(), { coalesce: { key: 'championship-commentary' } }),- ).rejects.toThrow('Agent event coalescing is not enabled on this server');- expect(methods.enqueueAgentTriggerDelivery).not.toHaveBeenCalled();- await service.stop();- });-it('refuses to arm without a reachable self origin', async () => {const service = createAgentTriggerService({ methods: deliveryMethods() });@@ -205,11 +187,10 @@ describe('durable agent trigger service', () => {await service.stop();});- it('persists terminal handling serialization only for opted-in bound continuations', async () => {+ it('persists terminal handling serialization only for bound continuations', async () => {const methods = deliveryMethods();const service = createAgentTriggerService({methods,- actorMailboxEnabled: () => true,deliveryOptions: { concurrency: 1, tickMs: 60_000 },});await service.initialize({ address: { address: '127.0.0.1', family: 'IPv4', port: 3080 } });@@ -228,23 +209,6 @@ describe('durable agent trigger service', () => {await service.stop();});- it('does not persist mailbox semantics before the rollout is enabled', async () => {- const methods = deliveryMethods();- const service = createAgentTriggerService({- methods,- actorMailboxEnabled: () => false,- deliveryOptions: { concurrency: 1, tickMs: 60_000 },- });- await service.initialize({ address: { address: '127.0.0.1', family: 'IPv4', port: 3080 } });-- await service.enqueue(boundEnvelope());-- expect(methods.enqueueAgentTriggerDelivery).toHaveBeenCalledWith(- expect.not.objectContaining({ awaitTerminalHandling: expect.anything() }),- );- await service.stop();- });-it('rejects enqueue before persistence when the principal was deleted', async () => {const methods = deliveryMethods();const service = createAgentTriggerService({diff --git a/packages/api/src/agents/triggers/service.ts b/packages/api/src/agents/triggers/service.tsindex fccc635d2a..549630c0fe 100644--- a/packages/api/src/agents/triggers/service.ts+++ b/packages/api/src/agents/triggers/service.ts@@ -15,13 +15,12 @@ import type {import type { AgentTriggerEnqueueOptions, PreparedAgentTriggerDelivery } from './delivery';import type { BoundAddress } from '../../app/origin';import { AgentTriggerDeliveryDeferredError, createAgentTriggerDeliveryEngine } from './engine';-import { AgentTriggerDeliveryError, prepareAgentTriggerDelivery } from './delivery';import { isShutdownInProgress, registerShutdownTask } from '../../app/shutdown';import { generateAgentTriggerToken } from '../../crypto/jwt';+import { prepareAgentTriggerDelivery } from './delivery';import { selfOriginFromAddress } from '../../app/origin';import { createAgentTriggerExecutionHost } from './host';import { parseAgentTriggerEnvelope } from './envelope';-import { isEnabled } from '../../utils/common';export const AGENT_TRIGGER_TOKEN_TTL = '60s';const DEFAULT_USER_DRAIN_TIMEOUT_MS = 35_000;@@ -46,8 +45,6 @@ export interface AgentTriggerServiceDeps {userDrainPollMs?: number;purgeRecoveryIntervalMs?: number;purgeRecoveryLimit?: number;- coalescingEnabled?: () => boolean;- actorMailboxEnabled?: () => boolean;}export interface AgentTriggerDeliveryReceipt {@@ -195,10 +192,6 @@ export function createAgentTriggerService(deps: AgentTriggerServiceDeps = {}): Aconst purgeRecoveryIntervalMs =deps.purgeRecoveryIntervalMs ?? DEFAULT_PURGE_RECOVERY_INTERVAL_MS;const purgeRecoveryLimit = deps.purgeRecoveryLimit ?? DEFAULT_PURGE_RECOVERY_LIMIT;- const coalescingEnabled =- deps.coalescingEnabled ?? (() => isEnabled(process.env.ENABLE_AGENT_EVENT_COALESCING));- const actorMailboxEnabled =- deps.actorMailboxEnabled ?? (() => isEnabled(process.env.ENABLE_AGENT_EVENT_ACTOR_MAILBOX));if (!Number.isSafeInteger(userDrainTimeoutMs) || userDrainTimeoutMs <= 0) {throw new TypeError('userDrainTimeoutMs must be a positive integer');}@@ -416,12 +409,8 @@ export function createAgentTriggerService(deps: AgentTriggerServiceDeps = {}): Adispatch: dispatchForActivePrincipal,enqueue: async (envelope, options) => {const methods = requireMethods();- if (options?.coalesce != null && !coalescingEnabled()) {- throw new AgentTriggerDeliveryError('Agent event coalescing is not enabled on this server');- }const prepared = prepareAgentTriggerDelivery(envelope, options);const awaitTerminalHandling =- actorMailboxEnabled() &&prepared.envelope.mode === 'continue' &&prepared.envelope.target.bindingId != null &&prepared.envelope.target.sourceKeyId != null;diff --git a/packages/api/src/app/agents.spec.ts b/packages/api/src/app/agents.spec.tsindex 0733ee6b96..4f1c2bfdc8 100644--- a/packages/api/src/app/agents.spec.ts+++ b/packages/api/src/app/agents.spec.ts@@ -5,11 +5,6 @@ describe('configureAgentEventRuntime', () => {beforeEach(() => {process.env = { ...originalEnvironment };- delete process.env.ENABLE_AGENT_EVENT_CHILD_TURNS;- delete process.env.ENABLE_SUBAGENT_COMPLETION_WAKEUPS;- delete process.env.ENABLE_AGENT_EVENT_COALESCING;- delete process.env.ENABLE_AGENT_EVENT_ACTOR_MAILBOX;- delete process.env.ENABLE_AGENT_EVENT_DURABLE_RECEIPTS;delete process.env.AGENT_TRIGGERS_SELF_URL;});@@ -17,39 +12,19 @@ describe('configureAgentEventRuntime', () => {process.env = originalEnvironment;});- it('projects explicit base-config rollout flags into the legacy runtime seam', () => {+ it('projects the explicit base-config routing choice', () => {configureAgentEventRuntime({- childTurns: true,- completionWakeups: false,- coalescing: true,- actorMailbox: true,- durableReceipts: true,selfUrl: 'https://triggers.internal',});- expect(process.env.ENABLE_AGENT_EVENT_CHILD_TURNS).toBe('true');- expect(process.env.ENABLE_SUBAGENT_COMPLETION_WAKEUPS).toBe('false');- expect(process.env.ENABLE_AGENT_EVENT_COALESCING).toBe('true');- expect(process.env.ENABLE_AGENT_EVENT_ACTOR_MAILBOX).toBe('true');- expect(process.env.ENABLE_AGENT_EVENT_DURABLE_RECEIPTS).toBe('true');expect(process.env.AGENT_TRIGGERS_SELF_URL).toBe('https://triggers.internal');});- it('preserves environment fallbacks when the YAML fields are omitted', () => {- process.env.ENABLE_AGENT_EVENT_CHILD_TURNS = 'true';- process.env.ENABLE_SUBAGENT_COMPLETION_WAKEUPS = 'true';- process.env.ENABLE_AGENT_EVENT_COALESCING = 'true';- process.env.ENABLE_AGENT_EVENT_ACTOR_MAILBOX = 'true';- process.env.ENABLE_AGENT_EVENT_DURABLE_RECEIPTS = 'true';+ it('preserves the environment routing fallback when YAML is omitted', () => {process.env.AGENT_TRIGGERS_SELF_URL = 'https://legacy.internal';configureAgentEventRuntime(undefined);- expect(process.env.ENABLE_AGENT_EVENT_CHILD_TURNS).toBe('true');- expect(process.env.ENABLE_SUBAGENT_COMPLETION_WAKEUPS).toBe('true');- expect(process.env.ENABLE_AGENT_EVENT_COALESCING).toBe('true');- expect(process.env.ENABLE_AGENT_EVENT_ACTOR_MAILBOX).toBe('true');- expect(process.env.ENABLE_AGENT_EVENT_DURABLE_RECEIPTS).toBe('true');expect(process.env.AGENT_TRIGGERS_SELF_URL).toBe('https://legacy.internal');});});diff --git a/packages/api/src/app/agents.ts b/packages/api/src/app/agents.tsindex 93b3474b97..6b6791b1d5 100644--- a/packages/api/src/app/agents.ts+++ b/packages/api/src/app/agents.ts@@ -2,19 +2,8 @@ import type { TAgentsEndpoint } from 'librechat-data-provider';type AgentEventRuntimeConfig = NonNullable<TAgentsEndpoint['eventDriven']>;-const setBooleanEnvironmentFallback = (name: string, value?: boolean): void => {- if (value != null) {- process.env[name] = String(value);- }-};--/** Applies base-config rollout flags before the HTTP listener accepts agent events. */+/** Applies the optional base-config routing choice before the event listener starts. */export const configureAgentEventRuntime = (config?: AgentEventRuntimeConfig): void => {- setBooleanEnvironmentFallback('ENABLE_AGENT_EVENT_CHILD_TURNS', config?.childTurns);- setBooleanEnvironmentFallback('ENABLE_SUBAGENT_COMPLETION_WAKEUPS', config?.completionWakeups);- setBooleanEnvironmentFallback('ENABLE_AGENT_EVENT_COALESCING', config?.coalescing);- setBooleanEnvironmentFallback('ENABLE_AGENT_EVENT_ACTOR_MAILBOX', config?.actorMailbox);- setBooleanEnvironmentFallback('ENABLE_AGENT_EVENT_DURABLE_RECEIPTS', config?.durableReceipts);if (config?.selfUrl != null) {process.env.AGENT_TRIGGERS_SELF_URL = config.selfUrl;}diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex be69d24140..e154e83fe8 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -67,7 +67,7 @@ describe('bedrockEndpointSchema', () => {});describe('agent event runtime config', () => {- it('accepts rollout flags and agent-event admission limits', () => {+ it('accepts the routing choice and ignores removed rollout fields', () => {const result = configSchema.safeParse({version: '1.0',endpoints: {@@ -93,12 +93,6 @@ describe('agent event runtime config', () => {return;}expect(result.data.endpoints?.agents?.eventDriven).toEqual({- childTurns: true,- completionWakeups: false,- coalescing: true,- actorMailbox: true,- checkpointForks: true,- durableReceipts: true,selfUrl: 'https://triggers.internal',});expect(result.data.rateLimits?.agentEvents).toEqual({@@ -107,7 +101,7 @@ describe('agent event runtime config', () => {});});- it('rejects checkpoint forks with the process-local memory checkpointer', () => {+ it('does not let removed checkpoint fields control memory-checkpointer validation', () => {const result = configSchema.safeParse({version: '1.0',endpoints: {@@ -118,14 +112,12 @@ describe('agent event runtime config', () => {},});- expect(result.success).toBe(false);- expect(result.error?.issues).toEqual(- expect.arrayContaining([- expect.objectContaining({- path: ['endpoints', 'agents', 'eventDriven', 'checkpointForks'],- }),- ]),- );+ expect(result.success).toBe(true);+ if (!result.success) {+ return;+ }+ expect(result.data.endpoints?.agents?.eventDriven).toEqual({});+ expect(result.data.endpoints?.agents?.checkpointer).toEqual({ type: 'memory' });});});diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex bb35b4e0f7..bec45ea212 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -1043,28 +1043,9 @@ export const agentsEndpointSchema = baseEndpointSchemaallowedEnvironments: z.array(z.enum(STATEFUL_CODE_ENVIRONMENTS)).min(1),}).optional(),- /** Process-wide event-driven agent rollout controls. Configure these from the base- * deployment config only so every API replica exposes the same wire capabilities. */+ /** Optional trusted origin for in-process agent event delivery. */eventDriven: z.object({- childTurns: z.boolean().optional(),- completionWakeups: z.boolean().optional(),- /** Enable only after every API worker can consume coalesced deliveries. */- coalescing: z.boolean().optional(),- /** Keep each bound actor's durable delivery lane queued through the- * admitted child turn's authoritative terminal outcome. */- actorMailbox: z.boolean().optional(),- /** Reuse a bound event actor's committed checkpoint through isolated- * per-invocation forks. Keep off until every API worker runs an SDK- * and host adapter that understand the fork lifecycle. */- checkpointForks: z.boolean().optional(),- /** Admit checkpoint-forked external actions through the durable- * delivery receipt protocol. Enable only after every API replica- * runs the token-fenced receipt implementation and pre-upgrade- * actor deliveries have drained. */- durableReceipts: z.boolean().optional(),- /** Optional trusted origin for in-process trigger delivery. The bound- * listener remains the default and is safer for most deployments. */selfUrl: z.string().url().optional(),}).optional(),@@ -1081,15 +1062,6 @@ export const agentsEndpointSchema = baseEndpointSchemacheckpointer: checkpointerSchema,}),)- .superRefine((config, ctx) => {- if (config.eventDriven?.checkpointForks === true && config.checkpointer?.type === 'memory') {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ['eventDriven', 'checkpointForks'],- message: 'Event actor checkpoint forks require the Mongo checkpointer',- });- }- }).default({disableBuilder: false,capabilities: defaultAgentCapabilities,