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
🚡 fix: Restore Enforced Model Specs for Agent Continuations (#17229)
lia-by-librechat[bot]20701bed06e2
diff --git a/api/server/middleware/buildEndpointOption.js b/api/server/middleware/buildEndpointOption.jsindex 42d114c34a..cb33cb4be1 100644--- a/api/server/middleware/buildEndpointOption.js+++ b/api/server/middleware/buildEndpointOption.js@@ -1,6 +1,7 @@const {handleError,applyModelSpecPreset,+ restoreAgentTriggerModelSpec,resolveModelSpecForEndpoint,resolveModelSpecPromptPrefixVariables,inspectContent,@@ -58,6 +59,7 @@ function inspectResolvedCurrentUser(req, promptPrefixTemplate) {}async function buildEndpointOption(req, res, next) {+ restoreAgentTriggerModelSpec(req);const { endpoint, endpointType } = req.body;const isAgents =isAgentsEndpoint(endpoint) || req.baseUrl.startsWith(EndpointURLs[EModelEndpoint.agents]);diff --git a/api/server/middleware/buildEndpointOption.spec.js b/api/server/middleware/buildEndpointOption.spec.jsindex b4ecd4cd61..a3c177c85a 100644--- a/api/server/middleware/buildEndpointOption.spec.js+++ b/api/server/middleware/buildEndpointOption.spec.js@@ -780,3 +780,287 @@ describe('buildEndpointOption - defaultParamsEndpoint parsing', () => {);});});++describe('buildEndpointOption - enforced server continuations', () => {+ const {+ createAgentTriggerExecutionHost,+ createAgentTriggerEnvelope,+ createSubagentThreadTurnGuard,+ generateAgentTriggerToken,+ isAgentTriggerRequest,+ handleError,+ } = require('@librechat/api');+ const savedSpec = {+ name: 'saved-agent',+ label: 'Saved Agent',+ preset: { endpoint: EModelEndpoint.agents, agent_id: 'agent-1' },+ };+ const config = { modelSpecs: { enforce: true, list: [savedSpec] } };+ const conversation = {+ user: 'user-1',+ tenantId: 'tenant-1',+ conversationId: 'conversation-1',+ agent_id: 'agent-1',+ spec: savedSpec.name,+ };+ let originalSecret;++ beforeEach(() => {+ jest.clearAllMocks();+ mockGetEndpointsConfig.mockResolvedValue({});+ originalSecret = process.env.JWT_SECRET;+ process.env.JWT_SECRET = 'continuation-test-signing-key';+ });++ afterEach(() => {+ if (originalSecret === undefined) delete process.env.JWT_SECRET;+ else process.env.JWT_SECRET = originalSecret;+ });++ it.each([+ ['agent-queued-turn', 'agent.queued-turn'],+ ['subagent-completion', 'subagent.completion'],+ ['background-tool-completion', 'background-tool.completion'],+ ['schedule', 'schedule.occurrence'],+ ['api', 'remote.event'],+ ['webhook', 'resource.ready'],+ ['queue', 'message.ready'],+ ])(+ 'admits a signed %s through the normal enforced endpoint builder',+ async (source, eventType) => {+ const getConvo = jest.fn(async () => conversation);+ const guard = createSubagentThreadTurnGuard({+ getConvo,+ store: { isThreadActiveForOwner: () => false },+ });+ const scheduled = ['schedule', 'api', 'webhook', 'queue'].includes(source);+ let admitted;+ const host = createAgentTriggerExecutionHost({+ getBaseUrl: () => 'http://localhost:3080',+ mintToken: () => generateAgentTriggerToken('user-1'),+ fetch: async (_url, init) => {+ const req = createReq(JSON.parse(init.body), config);+ req.baseUrl = '/api/agents/chat';+ req.user = { id: 'user-1', tenantId: 'tenant-1' };+ req._isAgentTrigger = isAgentTriggerRequest({+ headers: Object.fromEntries(+ Object.entries(init.headers).map(([key, value]) => [key.toLowerCase(), value]),+ ),+ });+ expect(req._isAgentTrigger).toBe(true);+ expect(req.body).not.toHaveProperty('spec');+ const next = jest.fn();+ // A cached authorization marker supplies no conversation document.+ await guard(req, createRes(), next);+ expect(next).toHaveBeenCalledWith();+ next.mockClear();+ await buildEndpointOption(req, createRes(), next);+ expect(handleError).not.toHaveBeenCalled();+ expect(next).toHaveBeenCalledWith();+ admitted = req.body.endpointOption;+ return new Response(+ JSON.stringify({+ status: 'started',+ streamId: 'stream-1',+ conversationId: 'conversation-1',+ }),+ { status: 200 },+ );+ },+ });+ const envelope = createAgentTriggerEnvelope({+ mode: scheduled ? 'fire' : 'continue',+ requestId: 'request-1',+ deliveryId: 'delivery-1',+ receivedAt: 1_000,+ principal: { id: 'user-1', tenantId: 'tenant-1' },+ target: {+ agentId: 'agent-1',+ ...(!scheduled && {+ conversationId: 'conversation-1',+ parentMessageId: 'assistant-1',+ }),+ },+ event: {+ id: 'event-1',+ type: eventType,+ occurredAt: 1_000,+ source: { id: source, type: scheduled ? source : 'internal' },+ payload: { spec: 'forged-spec' },+ },+ input: 'Continue the turn',+ });++ await expect(host.dispatch(envelope)).resolves.toMatchObject({ status: 'started' });+ expect(admitted).toMatchObject({ spec: savedSpec.name, agent_id: 'agent-1' });+ expect(getConvo).toHaveBeenCalledTimes(scheduled ? 0 : 1);+ },+ );++ it.each([undefined, 'saved-agent', 'removed-spec'])(+ 'runs the real guard for a signed binding with persisted spec %s',+ async (storedSpec) => {+ const bindingId = 'evtbind_test';+ const lineage = { parentConversationId: 'parent-1', parentAgentId: 'parent-agent' };+ const child = {+ user: 'user-1',+ tenantId: 'tenant-1',+ conversationId: 'actor-1',+ agent_id: 'agent-1',+ agentEventBinding: { bindingId, sourceKeyId: 'key-1', actorId: 'actor' },+ subagentThread: lineage,+ ...(storedSpec != null && { spec: storedSpec }),+ };+ const getConvo = jest.fn(async (_user, id) =>+ id === 'parent-1'+ ? { user: 'user-1', tenantId: 'tenant-1', conversationId: id, agent_id: 'parent-agent' }+ : child,+ );+ const getEventBinding = jest.fn(async () => ({+ conversationId: 'actor-1',+ agentId: 'agent-1',+ tenantId: 'tenant-1',+ binding: child.agentEventBinding,+ lineage,+ }));+ const guard = createSubagentThreadTurnGuard({+ getConvo,+ getEventBinding,+ store: { isThreadActiveForOwner: () => false },+ });+ const host = createAgentTriggerExecutionHost({+ getBaseUrl: () => 'http://localhost:3080',+ mintToken: () => generateAgentTriggerToken('user-1'),+ fetch: async (_url, init) => {+ const req = createReq(JSON.parse(init.body), config);+ req.baseUrl = '/api/agents/chat';+ req.user = { id: 'user-1', tenantId: 'tenant-1' };+ const headers = Object.fromEntries(+ Object.entries(init.headers).map(([key, value]) => [key.toLowerCase(), value]),+ );+ req._isAgentTrigger = isAgentTriggerRequest({ headers });+ req.get = (name) => headers[name.toLowerCase()];+ const next = jest.fn();+ await guard(req, createRes(), next);+ expect(next).toHaveBeenCalledWith();+ expect(req._agentEventBindingId).toBe(bindingId);+ expect(req.resolvedConversation.user).toBe('user-1');+ expect(req.resolvedConversation.spec).toBe(storedSpec);+ next.mockClear();+ await buildEndpointOption(req, createRes(), next);+ if (storedSpec === 'removed-spec') {+ expect(next).not.toHaveBeenCalled();+ expect(handleError).toHaveBeenCalledWith(expect.anything(), {+ text: 'No model spec selected',+ });+ } else {+ expect(handleError).not.toHaveBeenCalled();+ expect(next).toHaveBeenCalledWith();+ expect(req.body.endpointOption).toMatchObject({+ spec: savedSpec.name,+ agent_id: 'agent-1',+ });+ }+ expect(getConvo).toHaveBeenCalledTimes(2);+ expect(getEventBinding).toHaveBeenCalledWith({+ user: 'user-1',+ tenantId: 'tenant-1',+ bindingId,+ sourceKeyId: 'key-1',+ });+ return new Response(+ JSON.stringify({ status: 'started', streamId: 'actor-1', conversationId: 'actor-1' }),+ );+ },+ });+ await host.dispatch(+ createAgentTriggerEnvelope({+ mode: 'continue',+ requestId: 'request-1',+ deliveryId: 'delivery-1',+ receivedAt: 1_000,+ principal: { id: 'user-1', tenantId: 'tenant-1' },+ target: {+ agentId: 'agent-1',+ conversationId: 'actor-1',+ parentMessageId: 'root',+ bindingId,+ sourceKeyId: 'key-1',+ },+ event: {+ id: 'event-1',+ type: 'remote.event',+ occurredAt: 1_000,+ source: { id: 'remote', type: 'api' },+ },+ input: 'Handle this event',+ }),+ );+ },+ );++ it('still refuses an ordinary request carrying forged continuation metadata and a trigger marker', async () => {+ const req = createReq(+ {+ endpoint: EModelEndpoint.agents,+ agent_id: 'agent-1',+ conversationId: 'conversation-1',+ _isAgentTrigger: true,+ agentContinuationAdmission: { source: 'agent-queued-turn', spec: savedSpec.name },+ agentCompletion: { version: 1, sourceId: 'subagent-completion' },+ agentTrigger: {+ version: 1,+ event: {+ type: 'schedule.occurrence',+ occurredAt: 1_000,+ source: { type: 'schedule', id: 'schedule-1' },+ },+ },+ },+ config,+ );+ req.baseUrl = '/api/agents/chat';+ req.user = { id: 'user-1', tenantId: 'tenant-1' };+ req.resolvedConversation = conversation;+ req._isAgentTrigger = isAgentTriggerRequest({+ headers: { 'x-lc-agent-trigger': '1', authorization: 'Bearer forged' },+ });+ const res = createRes();+ const next = jest.fn();++ await buildEndpointOption(req, res, next);++ expect(handleError).toHaveBeenCalledWith(res, { text: 'No model spec selected' });+ expect(next).not.toHaveBeenCalled();+ expect(mockAgentBuildOptions).not.toHaveBeenCalled();+ });++ it.each(['explicit-invalid', 'wrong-endpoint'])(+ 'does not replace a supplied %s spec on a signed continuation',+ async (selected) => {+ const req = createReq(+ { endpoint: EModelEndpoint.agents, agent_id: 'agent-1', spec: selected },+ {+ modelSpecs: {+ enforce: true,+ list: [+ savedSpec,+ { name: 'wrong-endpoint', preset: { endpoint: EModelEndpoint.openAI } },+ ],+ },+ },+ );+ req._isAgentTrigger = true;+ req.resolvedConversation = conversation;+ const res = createRes();+ const next = jest.fn();++ await buildEndpointOption(req, res, next);++ expect(handleError).toHaveBeenCalledWith(res, {+ text: selected === 'explicit-invalid' ? 'Invalid model spec' : 'Model spec mismatch',+ });+ expect(next).not.toHaveBeenCalled();+ },+ );+});diff --git a/api/server/middleware/specs.spec.js b/api/server/middleware/specs.spec.jsnew file mode 100644index 0000000000..6cabacb9b2--- /dev/null+++ b/api/server/middleware/specs.spec.js@@ -0,0 +1,325 @@+const express = require('express');+const request = require('supertest');+const { processModelSpecs } = require('@librechat/data-schemas');+const { EModelEndpoint, specsConfigSchema } = require('librechat-data-provider');+const {+ createSubagentThreadTurnGuard,+ generateAgentTriggerToken,+ generateShortLivedToken,+ isAgentTriggerRequest,+ resolveModelSpecForEndpoint,+} = require('@librechat/api');++const mockGetAgent = jest.fn(async ({ id }) => ({+ id,+ _id: id,+ provider: EModelEndpoint.openAI,+ model: 'test-model',+}));+const mockCheckPermission = jest.fn(async ({ resourceId }) => resourceId === 'agent_B');++jest.mock('~/models', () => ({ getAgentWithVersionCount: mockGetAgent }));+jest.mock('~/server/services/PermissionService', () => ({+ checkPermission: mockCheckPermission,+}));+jest.mock('~/server/middleware/roles/capabilities', () => ({+ hasCapability: async () => false,+}));+jest.mock('~/server/services/Config', () => ({+ getEndpointsConfig: async () => ({}),+ getMCPServerTools: jest.fn(),+}));+jest.mock('~/server/services/MCP', () => ({ getAccessibleMCPServers: jest.fn() }));+jest.mock('~/server/services/Endpoints/assistants', () => ({ buildOptions: jest.fn() }));+jest.mock('~/server/services/Endpoints/azureAssistants', () => ({ buildOptions: jest.fn() }));+jest.mock('~/server/services/Endpoints/agents', () =>+ jest.requireActual('~/server/services/Endpoints/agents/build'),+);++const buildEndpointOption = require('./buildEndpointOption');+const { canAccessAgentFromBody } = require('./accessResources/canAccessAgentFromBody');++const spec = (agentId, name = 'shared', preset = {}, options = {}) => ({+ name,+ label: name,+ preset: { endpoint: EModelEndpoint.agents, agent_id: agentId, ...preset },+ ...options,+});++function createApp(mode, list, storedName = 'shared', endpoints) {+ const modelSpecs = processModelSpecs(endpoints, specsConfigSchema.parse({ enforce: true, list }));+ const child = {+ user: 'user-1',+ tenantId: 'tenant-1',+ conversationId: 'conversation-1',+ agent_id: 'agent_B',+ ...(mode === 'stored' && { spec: storedName }),+ ...(mode === 'binding' && {+ agentEventBinding: { bindingId: 'binding-1', sourceKeyId: 'key-1', actorId: 'actor-1' },+ subagentThread: { parentConversationId: 'parent-1', parentAgentId: 'agent_parent' },+ }),+ };+ const getConvo = jest.fn(async (_user, id) =>+ id === 'parent-1'+ ? { user: 'user-1', tenantId: 'tenant-1', conversationId: id, agent_id: 'agent_parent' }+ : child,+ );+ const guard = createSubagentThreadTurnGuard({+ getConvo,+ getEventBinding: async () => ({+ conversationId: child.conversationId,+ agentId: child.agent_id,+ tenantId: child.tenantId,+ binding: child.agentEventBinding,+ lineage: child.subagentThread,+ }),+ store: { isThreadActiveForOwner: () => false },+ });+ const state = {};+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'user-1', role: 'USER', tenantId: 'tenant-1' };+ req.config = { modelSpecs };+ req._isAgentTrigger = isAgentTriggerRequest(req);+ req.baseUrl = '/api/agents/chat';+ state.req = req;+ next();+ });+ app.post(+ '/chat',+ canAccessAgentFromBody({ requiredPermission: 1 }),+ guard,+ buildEndpointOption,+ async (req, res) => {+ const option = req.body.endpointOption;+ const agent = await option.agent;+ res.json({ spec: option.spec, agentId: option.agent_id, loadedAgentId: agent?.id });+ },+ );+ const post = ({ signed = true, selected } = {}) => {+ const token = signed ? generateAgentTriggerToken('user-1') : generateShortLivedToken('user-1');+ return request(app)+ .post('/chat')+ .set('Authorization', `Bearer ${token}`)+ .set('x-lc-agent-trigger', '1')+ .set('x-lc-agent-event-binding', 'binding-1')+ .set('x-lc-agent-event-source-key', 'key-1')+ .send({+ endpoint: EModelEndpoint.agents,+ agent_id: 'agent_B',+ ...(mode === 'fire'+ ? {+ newConversationId: 'conversation-1',+ agentTrigger: { version: 1, event: { source: { type: 'webhook' } } },+ }+ : { conversationId: 'conversation-1' }),+ ...(selected !== undefined && { spec: selected }),+ // Copying guard metadata into JSON must never establish trusted context.+ _isAgentTrigger: true,+ _agentEventBindingId: 'binding-1',+ });+ };+ return { modelSpecs, getConvo, state, post };+}++const cases = [+ {+ name: 'A first, B second with the same name',+ list: [spec('agent_A'), spec('agent_B')],+ canonicalAgent: 'agent_A',+ },+ {+ name: 'B first, A second with the same name',+ list: [spec('agent_B'), spec('agent_A')],+ canonicalAgent: 'agent_B',+ },+ {+ name: 'same-agent duplicate names with different presets',+ list: [+ spec('agent_B', 'shared', { temperature: 0.1 }),+ spec('agent_B', 'shared', { temperature: 0.9 }),+ ],+ canonicalAgent: 'agent_B',+ },+ {+ name: 'duplicate names across endpoints',+ list: [spec('agent_A', 'shared', { endpoint: EModelEndpoint.openAI }), spec('agent_B')],+ canonicalError: 'model-spec-mismatch',+ },+ {+ name: 'default and order flags cannot disambiguate names',+ list: [+ spec('agent_A', 'shared', {}, { default: true, order: 9 }),+ spec('agent_B', 'shared', {}, { order: 0 }),+ ],+ canonicalAgent: 'agent_A',+ },+ {+ name: 'an empty name cannot be restored',+ list: [spec('agent_B', '')],+ targetName: '',+ canonicalError: 'invalid-model-spec',+ },+ {+ name: 'agent IDs remain case-sensitive',+ list: [spec('agent_b')],+ canonicalAgent: 'agent_b',+ },+ {+ name: 'custom endpoint normalization cannot become the agents endpoint',+ list: [spec('agent_B', 'shared', { endpoint: 'OLLAMA' })],+ endpoints: { custom: [{ name: 'Ollama' }] },+ canonicalError: 'model-spec-mismatch',+ normalizedEndpoint: 'ollama',+ },+ {+ name: 'unrelated name collisions do not disable a unique target',+ list: [spec('agent_A', 'other'), spec('agent_C', 'other'), spec('agent_B')],+ canonicalAgent: 'agent_B',+ allowed: true,+ },+ {+ name: 'a unique healthy spec',+ list: [spec('agent_B')],+ canonicalAgent: 'agent_B',+ allowed: true,+ },+ {+ name: 'case-distinct names remain exact',+ list: [spec('agent_A', 'Shared'), spec('agent_B')],+ canonicalAgent: 'agent_B',+ allowed: true,+ },+ {+ name: 'whitespace-distinct names remain exact',+ list: [spec('agent_A', ' shared '), spec('agent_B')],+ canonicalAgent: 'agent_B',+ allowed: true,+ },+ {+ name: 'an omitted endpoint is materialized by the real loader',+ list: [spec('agent_B', 'shared', { endpoint: undefined })],+ canonicalAgent: 'agent_B',+ allowed: true,+ },+ {+ name: 'an explicit null endpoint is skipped by the real loader',+ list: [spec('agent_A', 'shared', { endpoint: null }), spec('agent_B')],+ canonicalAgent: 'agent_B',+ allowed: true,+ },+ {+ name: 'another named preset is ambiguous only for fallback',+ list: [spec('agent_B'), spec('agent_B', 'other')],+ canonicalAgent: 'agent_B',+ storedOnly: true,+ },+];++describe.each(['fire', 'binding', 'stored'])('enforced %s spec identity', (mode) => {+ beforeEach(() => jest.clearAllMocks());++ it.each(cases)(+ '$name',+ async ({+ list,+ canonicalAgent,+ canonicalError,+ allowed,+ storedOnly,+ targetName = 'shared',+ endpoints,+ normalizedEndpoint,+ }) => {+ const { modelSpecs, getConvo, state, post } = createApp(mode, list, targetName, endpoints);+ if (normalizedEndpoint) expect(modelSpecs.list[0].preset.endpoint).toBe(normalizedEndpoint);+ const canonical = resolveModelSpecForEndpoint({+ modelSpecs,+ spec: targetName,+ endpoint: EModelEndpoint.agents,+ });+ if (canonicalError) expect(canonical.error).toBe(canonicalError);+ else expect(canonical.modelSpec.preset.agent_id).toBe(canonicalAgent);++ const response = await post();+ expect(mockCheckPermission).toHaveBeenCalledTimes(1);+ expect(mockCheckPermission).toHaveBeenCalledWith(+ expect.objectContaining({ resourceId: 'agent_B' }),+ );+ expect(mockGetAgent).not.toHaveBeenCalledWith({ id: 'agent_A' });+ expect(getConvo).toHaveBeenCalledTimes({ fire: 0, binding: 2, stored: 1 }[mode]);++ if (allowed || (storedOnly && mode === 'stored')) {+ expect(response.body).toEqual({+ spec: 'shared',+ agentId: 'agent_B',+ loadedAgentId: 'agent_B',+ });+ expect(mockGetAgent).toHaveBeenCalledTimes(2); // Authorization read, then actual saved-agent load.+ expect(state.req.body.spec).toBe('shared');+ const restored = resolveModelSpecForEndpoint({+ modelSpecs,+ spec: state.req.body.spec,+ endpoint: EModelEndpoint.agents,+ });+ expect(restored.modelSpec.preset.agent_id).toBe('agent_B');+ } else {+ expect(response.text).toContain('No model spec selected');+ expect(state.req.body).not.toHaveProperty('spec');+ expect(mockGetAgent).toHaveBeenCalledTimes(1); // No agent initialization after authorization.+ }+ },+ );++ it.each([+ ['missing', 'Invalid model spec'],+ ['', 'No model spec selected'],+ [123, 'No model spec selected'],+ ])('does not repair explicit invalid spec %s', async (selected, error) => {+ const { state, post } = createApp(mode, [spec('agent_B')]);+ const response = await post({ selected });+ expect(response.text).toContain(error);+ expect(state.req.body.spec).toBe(selected);+ expect(mockGetAgent).toHaveBeenCalledTimes(1);+ });++ it('authorizes an explicit colliding name through the existing canonical resolver', async () => {+ const { state, post } = createApp(mode, [spec('agent_A'), spec('agent_B')]);+ const response = await post({ selected: 'shared' });+ expect(response.status).toBe(403);+ expect(state.req.body.spec).toBe('shared');+ expect(mockCheckPermission).toHaveBeenCalledWith(+ expect.objectContaining({ resourceId: 'agent_A' }),+ );+ expect(mockGetAgent).toHaveBeenCalledTimes(1); // Only the canonical agent's denied ACL lookup.+ });++ it('does not trust unsigned continuation metadata', async () => {+ const { post } = createApp(mode, [spec('agent_B')]);+ const response = await post({ signed: false });+ expect(response.text).toContain(mode === 'binding' ? 'view-only' : 'No model spec selected');+ expect(mockGetAgent).toHaveBeenCalledTimes(1);+ });+});++describe('stored continuation spec invalidation', () => {+ beforeEach(() => jest.clearAllMocks());++ it.each(['removed', 'retargeted'])(+ 'does not replace a %s stored spec with another agent preset',+ async (failure) => {+ const list = [spec('agent_B', 'replacement')];+ if (failure === 'retargeted') list.unshift(spec('agent_A'));+ const { state, post } = createApp('stored', list);+ const response = await post();+ expect(response.text).toContain('No model spec selected');+ expect(state.req.body).not.toHaveProperty('spec');+ expect(mockCheckPermission).toHaveBeenCalledWith(+ expect.objectContaining({ resourceId: 'agent_B' }),+ );+ expect(mockGetAgent).toHaveBeenCalledTimes(1);+ expect(mockGetAgent).not.toHaveBeenCalledWith({ id: 'agent_A' });+ },+ );+});diff --git a/packages/api/src/agents/guard.ts b/packages/api/src/agents/guard.tsindex 41e53d4114..7e0389105a 100644--- a/packages/api/src/agents/guard.ts+++ b/packages/api/src/agents/guard.ts@@ -106,6 +106,7 @@ async function isBoundEventContinuation(}return {[PARTIAL_RESOLVED_CONVERSATION]: true,+ user: target.userId,conversationId: binding.conversationId,agent_id: binding.agentId,...(binding.tenantId == null ? {} : { tenantId: binding.tenantId }),@@ -224,6 +225,9 @@ export function createSubagentThreadTurnGuard(deps: SubagentThreadWriteGuardDeps},);if (boundConversation != null) {+ if (resolvedConversation?.conversationId === boundConversation.conversationId) {+ boundConversation.spec = resolvedConversation.spec;+ }applyEventBindingContext(resolvedRequest, boundConversation);next();return;diff --git a/packages/api/src/modelSpecs/continuation.spec.ts b/packages/api/src/modelSpecs/continuation.spec.tsnew file mode 100644index 0000000000..16e8c14d2a--- /dev/null+++ b/packages/api/src/modelSpecs/continuation.spec.ts@@ -0,0 +1,214 @@+import { EModelEndpoint } from 'librechat-data-provider';+import type { TModelSpec } from 'librechat-data-provider';+import { restoreAgentTriggerModelSpec } from './continuation';++const spec: TModelSpec = {+ name: 'saved-agent',+ label: 'Saved Agent',+ preset: { endpoint: EModelEndpoint.agents, agent_id: 'agent-1' },+};++function request() {+ return {+ _isAgentTrigger: true,+ user: { id: 'user-1', tenantId: 'tenant-1' },+ config: { modelSpecs: { enforce: true, list: [spec] } },+ body: {+ endpoint: EModelEndpoint.agents,+ agent_id: 'agent-1',+ conversationId: 'conversation-1',+ } as Record<string, unknown>,+ resolvedConversation: {+ user: 'user-1',+ tenantId: 'tenant-1',+ conversationId: 'conversation-1',+ agent_id: 'agent-1',+ spec: 'saved-agent',+ },+ };+}++function scheduleRequest() {+ const req = request();+ delete req.body.conversationId;+ req.body.newConversationId = 'new-conversation';+ req.body.agentTrigger = {+ version: 1,+ event: {+ type: 'schedule.occurrence',+ occurredAt: 1_000,+ source: { type: 'schedule', id: 'schedule-1' },+ },+ };+ return req;+}++describe('trusted continuation model specs', () => {+ it.each(['agent-queued-turn', 'subagent-completion', 'background-tool-completion'])(+ 'restores the owned conversation spec for %s without using event metadata',+ (source) => {+ const req = request();+ req.body.agentContinuationAdmission = { source, spec: 'forged-spec' };+ req.body.agentCompletion = { version: 1, sourceId: source, spec: 'forged-spec' };+ restoreAgentTriggerModelSpec(req);+ expect(req.body.spec).toBe('saved-agent');+ },+ );++ it('selects the unique saved-agent spec for a new scheduled conversation', () => {+ const req = scheduleRequest();+ restoreAgentTriggerModelSpec(req);+ expect(req.body.spec).toBe('saved-agent');+ });++ it.each([request, scheduleRequest])(+ 'does not trust a forged trigger body or transport marker',+ (make) => {+ const req = make();+ req._isAgentTrigger = false;+ req.body._isAgentTrigger = true;+ req.body['x-lc-agent-trigger'] = '1';+ restoreAgentTriggerModelSpec(req);+ expect(req.body).not.toHaveProperty('spec');+ },+ );++ it.each(['user', 'tenantId', 'conversationId', 'agent_id', 'spec'] as const)(+ 'does not restore a mismatched conversation %s',+ (field) => {+ const req = request();+ req.resolvedConversation[field] = 'different';+ restoreAgentTriggerModelSpec(req);+ expect(req.body).not.toHaveProperty('spec');+ },+ );++ it.each(['explicit-spec', '', 123])(+ 'preserves an explicitly submitted spec %s for validation',+ (value) => {+ const req = request();+ req.body.spec = value;+ restoreAgentTriggerModelSpec(req);+ expect(req.body.spec).toBe(value);+ },+ );++ it.each(['agent_id', 'endpoint'] as const)(+ 'does not switch the authorized %s through a changed preset',+ (field) => {+ const req = request();+ req.config.modelSpecs.list = [{ ...spec, preset: { ...spec.preset, [field]: 'different' } }];+ restoreAgentTriggerModelSpec(req);+ expect(req.body).not.toHaveProperty('spec');+ },+ );++ it('fails closed when several schedule specs name the same agent', () => {+ const req = scheduleRequest();+ req.config.modelSpecs.list.push({ ...spec, name: 'other-preset' });+ restoreAgentTriggerModelSpec(req);+ expect(req.body).not.toHaveProperty('spec');+ });++ it('fails closed when the guard has no resolved conversation', () => {+ const { resolvedConversation: _conversation, ...req } = request();+ restoreAgentTriggerModelSpec(req);+ expect(req.body).not.toHaveProperty('spec');+ });++ it('does not infer a new conversation spec from unsigned schedule metadata', () => {+ const req = request();+ delete req.body.conversationId;+ restoreAgentTriggerModelSpec(req);+ expect(req.body).not.toHaveProperty('spec');+ });++ it.each(['api', 'webhook', 'queue', 'custom'])(+ 'restores a signed source-neutral %s fire',+ (source) => {+ const req = scheduleRequest();+ req.body.agentTrigger = { version: 1, event: { source: { type: source } } };+ restoreAgentTriggerModelSpec(req);+ expect(req.body.spec).toBe('saved-agent');+ },+ );++ it.each(['unsigned', 'ambiguous', 'invalid', 'retargeted'])(+ 'refuses a source-neutral fire that is %s',+ (failure) => {+ const req = scheduleRequest();+ req.body.agentTrigger = { version: 1, event: { source: { type: 'webhook' } } };+ if (failure === 'unsigned') req._isAgentTrigger = false;+ if (failure === 'ambiguous') req.config.modelSpecs.list.push({ ...spec, name: 'other' });+ if (failure === 'invalid') req.body.spec = 'invalid';+ if (failure === 'retargeted') req.body.agent_id = 'other-agent';+ restoreAgentTriggerModelSpec(req);+ expect(req.body.spec).toBe(failure === 'invalid' ? 'invalid' : undefined);+ },+ );++ function bindingRequest() {+ const req = request();+ const { spec: _spec, ...conversation } = req.resolvedConversation;+ return {+ ...req,+ _agentEventBindingId: 'binding-1',+ resolvedConversation: { ...conversation, agentEventBinding: { bindingId: 'binding-1' } },+ };+ }++ it('restores only a guard-authorized spec-less binding target', () => {+ const req = bindingRequest();+ restoreAgentTriggerModelSpec(req);+ expect(req.body.spec).toBe('saved-agent');+ });++ it.each(['user', 'tenantId', 'conversationId', 'agent_id'] as const)(+ 'refuses a binding with a mismatched %s',+ (field) => {+ const req = bindingRequest();+ req.resolvedConversation[field] = 'different';+ restoreAgentTriggerModelSpec(req);+ expect(req.body).not.toHaveProperty('spec');+ },+ );++ it.each(['unverified', 'unsigned', 'ambiguous', 'explicit', 'ordinary'])(+ 'does not widen fallback for an %s binding request',+ (failure) => {+ const req = bindingRequest();+ if (failure === 'unverified') req._agentEventBindingId = 'different';+ if (failure === 'unsigned') req._isAgentTrigger = false;+ if (failure === 'ambiguous') req.config.modelSpecs.list.push({ ...spec, name: 'other' });+ if (failure === 'explicit') req.body.spec = 'invalid';+ if (failure === 'ordinary') {+ req._agentEventBindingId = '';+ req.body._agentEventBindingId = 'binding-1';+ }+ restoreAgentTriggerModelSpec(req);+ expect(req.body.spec).toBe(failure === 'explicit' ? 'invalid' : undefined);+ },+ );++ it.each(['removed', 'retargeted'])(+ 'never reselects an ordinary conversation’s %s spec',+ (failure) => {+ const req = request();+ if (failure === 'removed') req.resolvedConversation.spec = 'removed';+ else+ req.config.modelSpecs.list = [+ { ...spec, preset: { ...spec.preset, agent_id: 'other-agent' } },+ ];+ req.config.modelSpecs.list.push({ ...spec, name: 'replacement' });+ restoreAgentTriggerModelSpec(req);+ expect(req.body).not.toHaveProperty('spec');+ },+ );++ it('leaves non-enforced requests unchanged', () => {+ const req = request();+ req.config.modelSpecs.enforce = false;+ restoreAgentTriggerModelSpec(req);+ expect(req.body).not.toHaveProperty('spec');+ });+});diff --git a/packages/api/src/modelSpecs/continuation.ts b/packages/api/src/modelSpecs/continuation.tsnew file mode 100644index 0000000000..0c1d67bf39--- /dev/null+++ b/packages/api/src/modelSpecs/continuation.ts@@ -0,0 +1,102 @@+import { EModelEndpoint, resolveModelSpecEndpoint } from 'librechat-data-provider';+import type { TSpecsConfig } from 'librechat-data-provider';++interface AgentTriggerModelSpecRequest {+ _isAgentTrigger?: boolean;+ _agentEventBindingId?: string;+ user?: { id?: string; tenantId?: string };+ config?: { modelSpecs?: Pick<TSpecsConfig, 'enforce' | 'list'> | null };+ body?: Record<string, unknown>;+ resolvedConversation?: {+ user?: string;+ tenantId?: string;+ conversationId: string;+ agent_id?: string;+ spec?: string | null;+ agentEventBinding?: { bindingId: string };+ } | null;+}++/** Restore server-started turns without changing the agent already authorized by the route. */+export function restoreAgentTriggerModelSpec(req: AgentTriggerModelSpecRequest): void {+ const { body } = req;+ const modelSpecs = req.config?.modelSpecs;+ if (+ req._isAgentTrigger !== true ||+ body == null ||+ body.spec != null ||+ body.endpoint !== EModelEndpoint.agents ||+ !modelSpecs?.enforce ||+ !modelSpecs.list?.length ||+ typeof body.agent_id !== 'string' ||+ !req.user?.id+ ) {+ return;+ }++ const matchesAgent = (spec: NonNullable<TSpecsConfig['list']>[number]): boolean =>+ resolveModelSpecEndpoint(spec) === body.endpoint && spec.preset.agent_id === body.agent_id;++ let storedSpec: string | null | undefined;++ if (body.conversationId != null) {+ // The subagent turn guard resolves this even on the cached authorization path.+ const conversation = req.resolvedConversation;+ if (+ conversation == null ||+ conversation.conversationId !== body.conversationId ||+ conversation.user !== req.user.id ||+ (conversation.tenantId ?? undefined) !== (req.user.tenantId ?? undefined) ||+ conversation.agent_id !== body.agent_id+ ) {+ return;+ }+ storedSpec = conversation.spec;+ // Only the guard can establish this binding context after checking its owner and parent.+ if (+ storedSpec == null &&+ (!req._agentEventBindingId ||+ conversation.agentEventBinding?.bindingId !== req._agentEventBindingId)+ ) {+ return;+ }+ } else {+ const trigger = body.agentTrigger;+ if (+ trigger == null ||+ typeof trigger !== 'object' ||+ Array.isArray(trigger) ||+ !('version' in trigger) ||+ trigger.version !== 1+ ) {+ return;+ }+ }+ // A stored name fixes the choice; new turns require exactly one matching agent preset.+ let selected: NonNullable<TSpecsConfig['list']>[number] | undefined;+ for (const spec of modelSpecs.list) {+ if (storedSpec != null ? spec.name !== storedSpec : !matchesAgent(spec)) {+ continue;+ }+ if (selected != null) {+ return;+ }+ selected = spec;+ }+ if (selected == null || !selected.name || !matchesAgent(selected)) {+ return;+ }++ // Downstream resolves by name, so a collision must not select a different preset.+ let foundName = false;+ for (const spec of modelSpecs.list) {+ if (spec.name !== selected.name) {+ continue;+ }+ if (foundName) {+ return;+ }+ foundName = true;+ }+ body.spec = selected.name;+}diff --git a/packages/api/src/modelSpecs/index.ts b/packages/api/src/modelSpecs/index.tsindex 167ed801a6..763ebd5f69 100644--- a/packages/api/src/modelSpecs/index.ts+++ b/packages/api/src/modelSpecs/index.ts@@ -294,3 +294,4 @@ export function sanitizeModelSpecs<T extends Partial<TSpecsConfig> | null | unde}export * from './reasoningOverride';export * from './persistedReasoningOverride';+export * from './continuation';