@@ -40,8 +40,16 @@ public static class AGUIEndpointRouteBuilderExtensions
4040 /// <param name="pattern">The URL pattern for the endpoint.</param>
4141 /// <returns>An <see cref="IEndpointConventionBuilder"/> for the mapped endpoint.</returns>
4242 /// <remarks>
43+ /// <para>
44+ /// Singleton registrations are resolved once when the endpoint is mapped. Scoped and transient registrations are
45+ /// resolved for each request as described in <see cref="MapAGUIServer(IEndpointRouteBuilder, string, string)"/>.
46+ /// In both cases, the session store is resolved for each request and persisted sessions are partitioned by the
47+ /// registration name.
48+ /// </para>
49+ /// <para>
4350 /// See <see cref="MapAGUIServer(IEndpointRouteBuilder, string, AIAgent)"/> for authentication,
4451 /// authorization, and caller-scoped session isolation requirements.
52+ /// </para>
4553 /// </remarks>
4654 public static IEndpointConventionBuilder MapAGUIServer (
4755 this IEndpointRouteBuilder endpoints ,
@@ -50,7 +58,16 @@ public static IEndpointConventionBuilder MapAGUIServer(
5058 {
5159 ArgumentNullException . ThrowIfNull ( endpoints ) ;
5260 ArgumentNullException . ThrowIfNull ( agentBuilder ) ;
53- return endpoints . MapAGUIServer ( agentBuilder . Name , pattern ) ;
61+
62+ if ( agentBuilder . Lifetime != ServiceLifetime . Singleton )
63+ {
64+ return endpoints . MapAGUIServer ( agentBuilder . Name , pattern ) ;
65+ }
66+
67+ string agentName = agentBuilder . Name ;
68+ var agent = endpoints . ServiceProvider . GetRequiredKeyedService < AIAgent > ( agentName ) ;
69+ return MapAGUIServerCore ( endpoints , pattern , context =>
70+ CreateHostAgent ( context . RequestServices , agent , agentName , sessionStorageIdentity : agentName ) ) ;
5471 }
5572
5673 /// <summary>
@@ -61,8 +78,17 @@ public static IEndpointConventionBuilder MapAGUIServer(
6178 /// <param name="pattern">The URL pattern for the endpoint.</param>
6279 /// <returns>An <see cref="IEndpointConventionBuilder"/> for the mapped endpoint.</returns>
6380 /// <remarks>
81+ /// <para>
82+ /// The keyed <see cref="AIAgent"/>, its keyed <see cref="AgentSessionStore"/>, and the
83+ /// <see cref="AgentIsolationKeyProvider"/> are resolved from <see cref="HttpContext.RequestServices"/>
84+ /// for each request, so the configured DI lifetime of the agent registration is honored.
85+ /// Persisted sessions are partitioned by <paramref name="agentName"/>, which remains stable across
86+ /// scoped or transient agent instances.
87+ /// </para>
88+ /// <para>
6489 /// See <see cref="MapAGUIServer(IEndpointRouteBuilder, string, AIAgent)"/> for authentication,
6590 /// authorization, and caller-scoped session isolation requirements.
91+ /// </para>
6692 /// </remarks>
6793 public static IEndpointConventionBuilder MapAGUIServer (
6894 this IEndpointRouteBuilder endpoints ,
@@ -72,8 +98,63 @@ public static IEndpointConventionBuilder MapAGUIServer(
7298 ArgumentNullException . ThrowIfNull ( endpoints ) ;
7399 ArgumentNullException . ThrowIfNull ( agentName ) ;
74100
75- var agent = endpoints . ServiceProvider . GetRequiredKeyedService < AIAgent > ( agentName ) ;
76- return endpoints . MapAGUIServer ( pattern , agent ) ;
101+ HostedAgentResolution . EnsureAgentRegistered ( endpoints . ServiceProvider , agentName ) ;
102+
103+ return MapAGUIServerCore ( endpoints , pattern , context =>
104+ {
105+ var agent = context . RequestServices . GetRequiredKeyedService < AIAgent > ( agentName ) ;
106+ return CreateHostAgent ( context . RequestServices , agent , agentName , sessionStorageIdentity : agentName ) ;
107+ } ) ;
108+ }
109+
110+ /// <summary>
111+ /// Maps an AG-UI agent endpoint that selects the agent to invoke for each request.
112+ /// </summary>
113+ /// <param name="endpoints">The endpoint route builder.</param>
114+ /// <param name="pattern">The URL pattern for the endpoint.</param>
115+ /// <param name="agentSelector">
116+ /// A delegate invoked once per request that returns the agent to invoke, or <see langword="null"/> when
117+ /// no agent matches the request. The delegate can use route values, claims, headers, and
118+ /// <see cref="HttpContext.RequestServices"/> to select or resolve the agent.
119+ /// </param>
120+ /// <returns>An <see cref="IEndpointConventionBuilder"/> for the mapped endpoint.</returns>
121+ /// <remarks>
122+ /// <para>
123+ /// When <paramref name="agentSelector"/> returns <see langword="null"/>, the endpoint responds with
124+ /// <c>404 Not Found</c> without loading session state.
125+ /// </para>
126+ /// <para>
127+ /// The selected agent's <see cref="AIAgent.Name"/> is its stable logical identity: it is used to resolve the
128+ /// keyed <see cref="AgentSessionStore"/> from <see cref="HttpContext.RequestServices"/> and to partition
129+ /// persisted sessions, so conversations continue across requests even when the selector returns a new agent
130+ /// instance each time. The selected agent must therefore have a non-empty name, and agents that must not
131+ /// share persisted sessions must have different names.
132+ /// </para>
133+ /// <para>
134+ /// Selection is not an authorization boundary. Enforce authorization with ASP.NET Core authorization
135+ /// policies, or return <see langword="null"/> from <paramref name="agentSelector"/> for agents the caller must
136+ /// not reach. See <see cref="MapAGUIServer(IEndpointRouteBuilder, string, AIAgent)"/> for authentication,
137+ /// authorization, and caller-scoped session isolation requirements.
138+ /// </para>
139+ /// </remarks>
140+ public static IEndpointConventionBuilder MapAGUIServer (
141+ this IEndpointRouteBuilder endpoints ,
142+ [ StringSyntax ( "route" ) ] string pattern ,
143+ Func < HttpContext , AIAgent ? > agentSelector )
144+ {
145+ ArgumentNullException . ThrowIfNull ( endpoints ) ;
146+ ArgumentNullException . ThrowIfNull ( agentSelector ) ;
147+
148+ return MapAGUIServerCore ( endpoints , pattern , context =>
149+ {
150+ if ( agentSelector ( context ) is not { } agent )
151+ {
152+ return null ;
153+ }
154+
155+ string agentName = HostedAgentResolution . GetSelectedAgentName ( agent ) ;
156+ return CreateHostAgent ( context . RequestServices , agent , agentName , sessionStorageIdentity : agentName ) ;
157+ } ) ;
77158 }
78159
79160 /// <summary>
@@ -88,6 +169,15 @@ public static IEndpointConventionBuilder MapAGUIServer(
88169 /// If an <see cref="AgentSessionStore"/> is registered in dependency injection keyed by the agent's name,
89170 /// it will be used to persist conversation sessions across requests using the AG-UI thread ID as the
90171 /// conversation identifier. If no session store is registered, sessions are ephemeral (not persisted).
172+ /// The supplied agent instance is used for every request, while the session store is resolved from
173+ /// <see cref="HttpContext.RequestServices"/> for each request.
174+ /// </para>
175+ /// <para>
176+ /// The agent's <see cref="AIAgent.Name"/> is its stable logical identity: it keys the session store and partitions
177+ /// persisted sessions, as it does for the named, hosted, and selector mappings. The same agent exposed through
178+ /// several mappings therefore continues the same conversations for a given thread ID, and so does any agent
179+ /// instance with the same name that uses the same session store. Agents that must not share persisted sessions must
180+ /// have different names. Sessions of an agent without a name are partitioned by its instance identity.
91181 /// </para>
92182 /// <para>
93183 /// <strong>Trust model.</strong> The AG-UI <c>RunAgentInput.ThreadId</c> arrives
@@ -125,18 +215,18 @@ public static IEndpointConventionBuilder MapAGUIServer(
125215 ArgumentNullException . ThrowIfNull ( endpoints ) ;
126216 ArgumentNullException . ThrowIfNull ( aiAgent ) ;
127217
128- var agentSessionStore = endpoints . ServiceProvider . GetKeyedService < AgentSessionStore > ( aiAgent . Name ) ;
129-
130- // Ensure that we have an IsolationKeyScopedAgentSessionStore registered.
131- var isolationKeyProvider = endpoints . ServiceProvider . GetService < AgentIsolationKeyProvider > ( ) ;
132- if ( agentSessionStore ? . GetService < IsolationKeyScopedAgentSessionStore > ( ) is null )
133- {
134- agentSessionStore ??= new NoopAgentSessionStore ( ) ;
135- agentSessionStore = new IsolationKeyScopedAgentSessionStore ( agentSessionStore , isolationKeyProvider , new ( ) { Strict = isolationKeyProvider != null } ) ;
136- }
137-
138- var hostAgent = new AIHostAgent ( aiAgent , agentSessionStore ) ;
218+ // A named agent is identified by its name, like the named, hosted, and selector mappings, so the same agent
219+ // exposed through several mappings continues the same conversations. Unnamed agents keep their instance identity.
220+ string ? sessionStorageIdentity = string . IsNullOrWhiteSpace ( aiAgent . Name ) ? null : aiAgent . Name ;
221+ return MapAGUIServerCore ( endpoints , pattern , context =>
222+ CreateHostAgent ( context . RequestServices , aiAgent , aiAgent . Name , sessionStorageIdentity ) ) ;
223+ }
139224
225+ private static IEndpointConventionBuilder MapAGUIServerCore (
226+ IEndpointRouteBuilder endpoints ,
227+ string pattern ,
228+ Func < HttpContext , AIHostAgent ? > hostAgentFactory )
229+ {
140230 IEndpointConventionBuilder endpoint = endpoints . MapPost ( pattern , async (
141231 [ FromBody ] RunAgentInput ? input ,
142232 [ FromServices ] IOptions < Microsoft . AspNetCore . Http . Json . JsonOptions > jsonOptions ,
@@ -148,6 +238,12 @@ public static IEndpointConventionBuilder MapAGUIServer(
148238 return Results . BadRequest ( ) ;
149239 }
150240
241+ // Resolve the agent before any session state is loaded so an unmatched selection never touches storage.
242+ if ( hostAgentFactory ( context ) is not { } hostAgent )
243+ {
244+ return Results . NotFound ( ) ;
245+ }
246+
151247 var jsonSerializerOptions = jsonOptions . Value . SerializerOptions ;
152248 var streamOptions = context . GetEndpoint ( ) ? . Metadata . GetMetadata < AGUIStreamOptions > ( )
153249 ?? context . RequestServices . GetService < IOptions < AGUIStreamOptions > > ( ) ? . Value ;
@@ -190,6 +286,25 @@ public static IEndpointConventionBuilder MapAGUIServer(
190286 return endpoint ;
191287 }
192288
289+ private static AIHostAgent CreateHostAgent (
290+ IServiceProvider services ,
291+ AIAgent agent ,
292+ string ? sessionStoreKey ,
293+ string ? sessionStorageIdentity )
294+ {
295+ var agentSessionStore = services . GetKeyedService < AgentSessionStore > ( sessionStoreKey ) ;
296+
297+ // Ensure that we have an IsolationKeyScopedAgentSessionStore registered.
298+ var isolationKeyProvider = services . GetService < AgentIsolationKeyProvider > ( ) ;
299+ if ( agentSessionStore ? . GetService < IsolationKeyScopedAgentSessionStore > ( ) is null )
300+ {
301+ agentSessionStore ??= new NoopAgentSessionStore ( ) ;
302+ agentSessionStore = new IsolationKeyScopedAgentSessionStore ( agentSessionStore , isolationKeyProvider , new ( ) { Strict = isolationKeyProvider != null } ) ;
303+ }
304+
305+ return new AIHostAgent ( agent , agentSessionStore , sessionStorageIdentity ) ;
306+ }
307+
193308 private static void MarkFeatureUsed ( )
194309 {
195310#pragma warning disable MAAI001
0 commit comments