mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
a12cc3878e
* Consolidate Foundry chat client decorators into FoundryChatClient
- Replace AzureAIProjectChatClient and AzureAIProjectResponsesChatClient with a single internal sealed FoundryChatClient that covers three modes (pure responses, server-side agent reference, hosted agent endpoint).
- Rename AzureAIProjectChatClientExtensions to AIProjectClientExtensions to reflect that it extends AIProjectClient.
- All four AsAIAgent extension overloads and both FoundryAgent constructors now construct FoundryChatClient internally so the microsoft.foundry telemetry tag is uniform across paths.
- Introduce AgentFrameworkUserAgentPolicy that stamps agent-framework-dotnet/{version} on outbound requests, mirroring the Python agent-framework-python/{version} contract.
- Delete the Foundry-local MeaiUserAgentPolicy duplicate; rely on MEAI 10.5.1 to stamp MEAI/{version} automatically.
- HostedAgentUserAgentPolicy keeps the combined foundry-hosting/agent-framework-dotnet/{version} segment (Python parity) and upgrades the bare segment in place to avoid duplication.
- Tests reorganized: FoundryChatClientTests, AIProjectClientExtensionsTests, AgentFrameworkUserAgentPolicyTests, MeaiAutoUserAgentVerificationTests, plus in-place upgrade unit tests in HostedOutboundUserAgentTests.
* Promote FoundryChatClient to public; add file/vector-store helpers and ToPromptAgentAsync converter
- Promote FoundryChatClient from internal sealed to public sealed for Python parity, so .NET developers can hold and pass a FoundryChatClient directly the way Python developers do.
- Mode 3 (hosted agent endpoint) now materializes an AIProjectClient from the parsed project root, making GetService<AIProjectClient>() non-null across all three construction modes. This eliminates the per-mode asymmetry that previously hid project-level helpers from agents constructed via an agent endpoint URL.
- Add four new instance methods on FoundryChatClient mirroring Python's spec: UploadFileAsync, DeleteFileAsync, CreateVectorStoreAsync (bundles upload + create + wait), DeleteVectorStoreAsync. Single overload each, path-only inputs to start; additional overloads can be added later without breaking callers. All are Experimental, consistent with the rest of the Foundry package.
- Add ToPromptAgentAsync extension methods on ChatClientAgent and FoundryAgent for the agent-to-prompt-agent converter described in the Foundry spec. Mode 1 (responses API) synthesizes a DeclarativeAgentDefinition from the agent's ChatOptions; mode 2 (server-side agent reference, version, or record) returns the cached or freshly fetched Definition; mode 3 throws InvalidOperationException because no local definition exists to convert.
- Strict AITool to ResponseTool mapping for mode 1: AIFunction becomes CreateFunctionTool with the function's JSON schema; AITool instances that wrap a ResponseTool unwrap via GetService(typeof(ResponseTool)); anything else throws InvalidOperationException naming the offending tool type. Matches the Python spec's unsupported-tools-raise-ValueError contract.
- New unit tests: FoundryChatClientVectorStoreTests (22 tests covering all four helpers across the three FoundryChatClient construction modes plus validation and cancellation), FoundryPromptAgentConverterTests (16 tests covering both extension entry points across mode 1 synthesis, mode 2 cached and fetched paths, all failure modes, and a Python-parity guard asserting both extensions produce equivalent definitions for equivalent inputs), plus four new tests in FoundryChatClientTests for the mode 3 AIProjectClient materialization.
* Stop building duplicate ProjectOpenAIClient in FoundryAgent agent-endpoint ctor
After Plan #2's mode-3 AIProjectClient materialization, the inner FoundryChatClient already exposes a project-level AIProjectClient (via GetService) that internally provides the project-level ProjectOpenAIClient via GetProjectOpenAIClient(). FoundryAgent's agent-endpoint constructor was still independently constructing a second project-level ProjectOpenAIClient via the now-redundant CreateProjectLevelOpenAIClientFromAgentEndpoint helper — two handles to the same logical resource.
Refactor: the agent-endpoint constructor now reads the inner FoundryChatClient's materialized AIProjectClient via base.GetService(typeof(AIProjectClient)) and derives the project-level ProjectOpenAIClient from it. The dead helper on both FoundryAgent (private static wrapper) and FoundryChatClient (the actual implementation) is removed. The user-supplied per-agent ClientPipelineOptions primitives (Transport, RetryPolicy, NetworkTimeout, UserAgentApplicationId) are propagated into the materialized AIProjectClientOptions so test-injected transports and explicit retry / timeout / user-agent settings reach the project-level pipeline — preserving the behavior the dead helper used to provide.
Updated AgentEndpointConstructor_GetServiceAIProjectClient_ReturnsNull to its now-correct counterpart AgentEndpointConstructor_GetServiceAIProjectClient_ReturnsNonNull, since after Plan #2 the agent-endpoint ctor surfaces a non-null AIProjectClient (per user direction in Plan #2 Q2).
* Strip duplicated AIProjectClient/ProjectOpenAIClient state from FoundryAgent
Both _aiProjectClient and _projectOpenAIClient fields on FoundryAgent were redundant:
- _aiProjectClient: FoundryAgent's GetService<AIProjectClient> override returned this field, but DelegatingAIAgent.GetService → ChatClientAgent.GetService → FoundryChatClient.GetService<AIProjectClient> already returns the same instance through the delegating chain. Field + override are pure duplication.
- _projectOpenAIClient: only used by FoundryAgent's own GetService<ProjectOpenAIClient> override and by CreateConversationSessionAsync. Per user direction, ProjectOpenAIClient is no longer exposed via GetService on either FoundryChatClient or FoundryAgent — callers retrieve it from the AIProjectClient themselves (aiProjectClient.GetProjectOpenAIClient()) the same way the framework does internally. This eliminates the mode-3 asymmetry where the chat client's stored ProjectOpenAIClient was per-agent (URL /agents/{name}/endpoint/protocols/openai) while the agent's was project-level.
Refactor:
- Delete both fields on FoundryAgent and the GetService override.
- Delete the ProjectOpenAIClient branch from FoundryChatClient.GetService.
- CreateConversationSessionAsync now resolves AIProjectClient at call time via this.GetService<AIProjectClient>() and derives the conversations client from it.
- Update FoundryChatClient tests that asserted on GetService<ProjectOpenAIClient> to assert Null (deliberate removal).
- Update FoundryAgent tests AgentEndpointConstructor_GetServiceProjectOpenAIClient_ReturnsNonNull and ProjectEndpointConstructor_GetServiceProjectOpenAIClient_ReturnsNonNull to ...ReturnsNull, and rewrite AgentEndpointConstructor_PropagatesUserAgentApplicationId_ToProjectLevelClient to look up AIProjectClient instead.
No production code (only tests) referenced GetService<ProjectOpenAIClient>, so this is a safe surface reduction. Net: 30 insertions, 61 deletions; FoundryAgent shrinks to a pure delegator with only the two convenience methods (CreateSessionAsync, CreateConversationSessionAsync) on top of the delegating chain.
* Rename FoundryChatClient.HostedAgentName to AgentName and populate it for mode 2
The previous name implied a mode 3 only property tied to the hosted-agent endpoint URL. Today only hosted endpoints surface this name, but conceptually an agent name exists for every server-side agent the client talks to. Renaming to AgentName makes the property general-purpose and ready for future modes where the same chat client may target other server-side agent shapes that are not necessarily 'hosted'.
Mode 2 (server-side agent reference) now mirrors AgentReference.Name into AgentName so callers have a uniform handle regardless of construction mode:
* Mode 1 (pure responses): AgentName is null. There is no agent.
* Mode 2 (AgentReference): AgentName == AgentReference.Name.
* Mode 3 (agent endpoint URL): AgentName is parsed from the URL segment as before.
Converter discriminator update: FoundryPromptAgentConverter previously used 'HostedAgentName is not null' to detect mode 3 and reject it. Now that mode 2 also populates AgentName, the mode 3 guard moves to the end of the resolution chain and uses the unambiguous 'AgentName is set AND no AgentReference exists' test. The user-visible error message and behavior are preserved.
Dead-state cleanup spotted during format verify:
* IDE0052 surfaced that FoundryChatClient._projectOpenAIClient is never read since the prior refactor stopped exposing ProjectOpenAIClient via GetService and rewired CreateConversationSessionAsync to resolve the AIProjectClient through the delegating chain. The field is deleted and its three ctor assignments removed.
* HostedAgentEndpointInner.PerAgentClient only existed to plumb the per-agent ProjectOpenAIClient into that now-deleted field, so the property and its ctor parameter are removed. The local 'perAgentClient' variable inside BuildHostedAgentEndpointInner is still needed to derive the inner IChatClient, but no longer escapes the helper.
Tests:
* Mode1_PureResponses_ReturnsNullForAgentSpecificServices now also asserts AgentName is null.
* New Mode2_AgentReference_PopulatesAgentNameFromAgentReference asserts the mode 2 mirror.
* Mode3_HostedAgentEndpoint_ParsesAgentNameFromUrl renamed assertion target HostedAgentName to AgentName.
Verification: 335/335 net10.0, 273/273 net472 Foundry unit; 229/229 Foundry.Hosting unit; format-verify (WSL2 + Docker mcr.microsoft.com/dotnet/sdk:10.0) clean on Microsoft.Agents.AI.Foundry.
* Adopt canonical mode names: Responses Agent, Prompt Agent, Agent Endpoint
Three FoundryChatClient construction modes now have one canonical noun used everywhere.
* Responses Agent (Mode 1): inline ChatClientAgent, project-level Responses API, no server-side def.
* Prompt Agent (Mode 2): server-side ProjectsAgentDefinition invoked by AgentReference.
* Agent Endpoint (Mode 3): per-agent URL /agents/{name}/endpoint/protocols/openai. Hosted-or-not.
'Hosted' stays the kind of agent (Microsoft.Agents.AI.Foundry.Hosting). Not synonym of Mode 3.
Rings:
1. XML docs + error messages use canonical names. en-GB to en-US: centralises, synthesise.
2. HostedAgentEndpointInner -> AgentEndpointInner, BuildHostedAgentEndpointInner -> BuildAgentEndpointInner.
3. Tests: Mode1_PureResponses_* -> Mode1_ResponsesAgent_*, Mode2_AgentReference_* -> Mode2_PromptAgent_*, Mode3_HostedAgentEndpoint_* -> Mode3_AgentEndpoint_*.
Pure rename. No behavior change. 335/335 net10 + 273/273 net472 unit, format clean.
* Address PR #5940 design feedback (Q-A through Q-F)
Q-A: poll vector store til status leaves InProgress before return. Exp backoff 250ms-2s. Honor cancel.
Q-B: try/catch upload loop. Mid-fail = best-effort DeleteFileAsync on already-uploaded ids. Swallow cleanup errors.
Q-C: pinned AgentReference.Version uses GetAgentVersionAsync. Empty/whitespace/'latest' = GetLatest path.
Q-D: HostedAgentUserAgentPolicy detects existing combined 'foundry-hosting/...' segment. No double prefix.
Q-E: mode-3 vector-store test uses fake transport. No DNS to example.com.
Q-F: no shim. Class always [Experimental] (since 8015e00f5, before dotnet-1.0.0). No compat contract. Callers rename to AIProjectClientExtensions.
Rebase onto origin/main reconciliation: aad20c2b3 added public AsAIAgent(this AIProjectClient, Uri agentEndpoint, ...) extension that calls an internal FoundryAgent(AIProjectClient, Uri, ...) ctor. Reintroduced that ctor + a new FoundryChatClient(AIProjectClient, Uri, ProjectOpenAIClientOptions?) overload that reuses the supplied AIProjectClient's pipeline (via GetProjectResponsesClientForAgentEndpoint) instead of stamping a fresh credential.
Verified: 346/346 net10 + 284/284 net472 Foundry unit, 230/230 Foundry.Hosting unit, format clean.
* Add FoundryAgent helper extensions: UploadFile/DeleteFile/CreateVectorStore/DeleteVectorStore
4 thin forwarders on FoundryAgent that route to the inner FoundryChatClient's helpers via agent.GetService<FoundryChatClient>().X(). Live in existing FoundryAgentExtensions.cs alongside ToPromptAgentAsync.
Throws InvalidOperationException when agent does not expose a FoundryChatClient via GetService (same pattern as ToPromptAgentAsync).
Unit tests: FoundryAgentExtensionsTests covers all 4 forwarders + null-agent ArgumentNullException for each. 8 new tests, 354/354 net10 + 292/292 net472.
Integration tests: parallel FoundryAgentExtensionsTests under Foundry.IntegrationTests mirrors the existing CreateAgent_CreatesAgentWithVectorStoresAsync shape (upload -> create vector store -> FileSearch tool answers question -> cleanup), but routes every helper call through the new FoundryAgent extensions. 4 new IT tests, all verified pass live against the real Foundry project (12-30s each). Skipped by default like the existing vector-store IT.
* Address Sergey's PR review comments
#1 (FoundryAgent.cs:139): drop unused aiProjectClient param from internal FoundryAgent(AIProjectClient, ChatClientAgent) ctor. Was discarded after null-check. Inner FoundryChatClient already surfaces AIProjectClient via GetService. 3 call sites in AIProjectClientExtensions updated.
#2 (FoundryChatClient.cs:376): add pollingTimeout param to CreateVectorStoreAsync. Defaults to 5 min, configurable, Timeout.InfiniteTimeSpan disables. Throws TimeoutException with vector store id and elapsed seconds when bound exceeded. CancellationToken still wins. New unit test PollingTimeout_ThrowsTimeoutExceptionAsync. FoundryAgentExtensions forwarder updated to plumb the new param.
Verified: 355/355 net10 + 293/293 net472 Foundry unit, 230/230 Foundry.Hosting unit, format clean.
421 lines
19 KiB
C#
421 lines
19 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
|
|
using System;
|
|
using System.ClientModel;
|
|
using System.ClientModel.Primitives;
|
|
using System.Collections.Generic;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Azure.AI.Extensions.OpenAI;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting.Server;
|
|
using Microsoft.AspNetCore.TestHost;
|
|
using Microsoft.Extensions.AI;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OpenAI;
|
|
|
|
#pragma warning disable OPENAI001, SCME0001, SCME0002, MEAI001
|
|
|
|
namespace Microsoft.Agents.AI.Foundry.Hosting.UnitTests;
|
|
|
|
/// <summary>
|
|
/// End-to-end tests that exercise the FULL hosted ASP.NET Core pipeline:
|
|
/// inbound HTTP → MapFoundryResponses → AgentFrameworkResponseHandler → TryApplyUserAgent →
|
|
/// agent invocation → outbound HTTP from inside the hosted environment.
|
|
/// Verifies that the hosted-agent <c>User-Agent</c> supplement reaches the outbound wire,
|
|
/// not just the inbound request.
|
|
/// </summary>
|
|
public sealed class HostedOutboundUserAgentTests : IAsyncDisposable
|
|
{
|
|
private const string TestEndpoint = "https://fake-foundry.example.com/api/projects/fake-prj";
|
|
private const string Deployment = "fake-deployment";
|
|
|
|
private WebApplication? _app;
|
|
private HttpClient? _inboundClient;
|
|
private RecordingHandler? _outboundHandler;
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
this._inboundClient?.Dispose();
|
|
this._outboundHandler?.Dispose();
|
|
if (this._app is not null)
|
|
{
|
|
await this._app.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Hosted_InboundResponsesRequest_TriggersOutboundCall_WithFoundryHostingSupplementAsync()
|
|
{
|
|
// Arrange: spin up a real ASP.NET Core TestServer that hosts an AIAgent backed by MEAI's
|
|
// OpenAIResponsesChatClient → ProjectResponsesClient → fake HTTP transport. This is the
|
|
// exact production stack minus the network: the only thing not real is the wire transport.
|
|
await this.StartHostedServerAsync();
|
|
|
|
// Act: send an inbound /openai/v1/responses request as the Foundry runtime would.
|
|
using var inboundRequest = new HttpRequestMessage(HttpMethod.Post, "/responses")
|
|
{
|
|
Content = new StringContent(InboundResponsesRequestJson(), Encoding.UTF8, "application/json"),
|
|
};
|
|
using var inboundResponse = await this._inboundClient!.SendAsync(inboundRequest);
|
|
var inboundBody = await inboundResponse.Content.ReadAsStringAsync();
|
|
|
|
// Assert: at least one OUTBOUND request reached the fake transport, AND it carries the
|
|
// combined hosted segment foundry-hosting/agent-framework-dotnet/{version} on its
|
|
// User-Agent. This matches Python's contract
|
|
// (foundry-hosting/agent-framework-python/{version}, see
|
|
// python/packages/core/agent_framework/_telemetry.py): a single combined segment when
|
|
// hosted, never two separate ones. The bare agent-framework-dotnet/{version} segment
|
|
// (from AgentFrameworkUserAgentPolicy in FoundryChatClient) must be upgraded in place
|
|
// by HostedAgentUserAgentPolicy — never appear duplicated.
|
|
Assert.True(this._outboundHandler!.Requests.Count > 0,
|
|
$"Expected at least one outbound request. Inbound status: {(int)inboundResponse.StatusCode}, body: {inboundBody}");
|
|
var outbound = this._outboundHandler.Requests[0];
|
|
Assert.StartsWith(TestEndpoint, outbound.Uri);
|
|
Assert.Contains("MEAI/", outbound.UserAgent);
|
|
Assert.Contains("foundry-hosting/agent-framework-dotnet/", outbound.UserAgent);
|
|
|
|
// The bare agent-framework-dotnet/{v} segment must NOT appear separately when the
|
|
// combined form is present — Python emits a single combined value when the hosted
|
|
// prefix is registered, and .NET preserves that contract via the in-place upgrade in
|
|
// HostedAgentUserAgentPolicy.
|
|
var combinedIdx = outbound.UserAgent!.IndexOf("foundry-hosting/agent-framework-dotnet/", StringComparison.Ordinal);
|
|
var beforeCombined = outbound.UserAgent.Substring(0, combinedIdx);
|
|
var afterCombined = outbound.UserAgent.Substring(combinedIdx + "foundry-hosting/agent-framework-dotnet/".Length);
|
|
Assert.DoesNotContain("agent-framework-dotnet/", beforeCombined);
|
|
Assert.DoesNotContain("agent-framework-dotnet/", afterCombined);
|
|
}
|
|
|
|
private async Task StartHostedServerAsync()
|
|
{
|
|
var builder = WebApplication.CreateBuilder();
|
|
builder.WebHost.UseTestServer();
|
|
|
|
// Build a real ChatClientAgent whose IChatClient is MEAI's OpenAIResponsesChatClient
|
|
// wrapping a ProjectResponsesClient backed by a fake HTTP handler. After AgentFrameworkResponseHandler
|
|
// resolves this agent, TryApplyUserAgent will swap the inner _responseClient with our wrapper.
|
|
this._outboundHandler = new RecordingHandler(MinimalResponseJson());
|
|
#pragma warning disable CA5399
|
|
var outboundHttpClient = new HttpClient(this._outboundHandler);
|
|
#pragma warning restore CA5399
|
|
|
|
var projectOptions = new ProjectResponsesClientOptions
|
|
{
|
|
Transport = new HttpClientPipelineTransport(outboundHttpClient),
|
|
};
|
|
var projectResponsesClient = new ProjectResponsesClient(
|
|
new Uri(TestEndpoint),
|
|
new FakeAuthenticationTokenProvider(),
|
|
projectOptions);
|
|
|
|
IChatClient chatClient = projectResponsesClient.AsIChatClient(Deployment);
|
|
AIAgent agent = new ChatClientAgent(chatClient);
|
|
|
|
builder.Services.AddFoundryResponses(agent);
|
|
builder.Services.AddSingleton<HostedSessionIsolationKeyProvider>(new FakeHostedSessionIsolationKeyProvider());
|
|
builder.Services.AddLogging();
|
|
|
|
this._app = builder.Build();
|
|
this._app.MapFoundryResponses();
|
|
|
|
await this._app.StartAsync();
|
|
|
|
var testServer = this._app.Services.GetRequiredService<IServer>() as TestServer
|
|
?? throw new InvalidOperationException("TestServer not found");
|
|
|
|
this._inboundClient = testServer.CreateClient();
|
|
}
|
|
|
|
private static string InboundResponsesRequestJson() => """
|
|
{
|
|
"model": "fake-deployment",
|
|
"input": [
|
|
{
|
|
"type": "message",
|
|
"id": "msg_1",
|
|
"status": "completed",
|
|
"role": "user",
|
|
"content": [{ "type": "input_text", "text": "Hello" }]
|
|
}
|
|
]
|
|
}
|
|
""";
|
|
|
|
private static string MinimalResponseJson() => """
|
|
{
|
|
"id":"resp_1","object":"response","created_at":1700000000,"status":"completed",
|
|
"model":"fake","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}
|
|
}
|
|
""";
|
|
|
|
[Fact]
|
|
public void TryApplyUserAgent_RepeatedCalls_OnSameAgent_RegistersPolicyOnce()
|
|
{
|
|
// Arrange: hosted resolution calls TryApplyUserAgent on every request. Without per-instance
|
|
// dedup, each call would append another policy entry to the shared OpenAIRequestPolicies,
|
|
// producing unbounded growth on singleton agents (one chat client reused across requests).
|
|
using var http = new HttpClient(new NoopHandler());
|
|
var openAIClient = new OpenAIClient(new ApiKeyCredential("fake"),
|
|
new OpenAIClientOptions { Transport = new HttpClientPipelineTransport(http) });
|
|
IChatClient chatClient = openAIClient.GetResponsesClient().AsIChatClient();
|
|
AIAgent agent = new ChatClientAgent(chatClient);
|
|
|
|
// Act
|
|
for (int i = 0; i < 50; i++)
|
|
{
|
|
FoundryHostingExtensions.TryApplyUserAgent(agent);
|
|
}
|
|
|
|
// Assert: exactly one HostedAgentUserAgentPolicy entry on the shared OpenAIRequestPolicies.
|
|
var policies = chatClient.GetService<OpenAIRequestPolicies>();
|
|
Assert.NotNull(policies);
|
|
Assert.Equal(1, EntriesCount(policies!));
|
|
}
|
|
|
|
[Fact]
|
|
public void TryApplyUserAgent_AcrossDistinctAgents_RegistersPolicyOncePerChatClient()
|
|
{
|
|
// Arrange: dedup is per-OpenAIRequestPolicies-instance, not global, so two agents on
|
|
// different chat clients each get exactly one registration.
|
|
using var http1 = new HttpClient(new NoopHandler());
|
|
using var http2 = new HttpClient(new NoopHandler());
|
|
var client1 = new OpenAIClient(new ApiKeyCredential("k1"),
|
|
new OpenAIClientOptions { Transport = new HttpClientPipelineTransport(http1) });
|
|
var client2 = new OpenAIClient(new ApiKeyCredential("k2"),
|
|
new OpenAIClientOptions { Transport = new HttpClientPipelineTransport(http2) });
|
|
|
|
IChatClient cc1 = client1.GetResponsesClient().AsIChatClient();
|
|
IChatClient cc2 = client2.GetResponsesClient().AsIChatClient();
|
|
AIAgent a1 = new ChatClientAgent(cc1);
|
|
AIAgent a2 = new ChatClientAgent(cc2);
|
|
|
|
// Act
|
|
for (int i = 0; i < 10; i++)
|
|
{
|
|
FoundryHostingExtensions.TryApplyUserAgent(a1);
|
|
FoundryHostingExtensions.TryApplyUserAgent(a2);
|
|
}
|
|
|
|
// Assert
|
|
Assert.Equal(1, EntriesCount(cc1.GetService<OpenAIRequestPolicies>()!));
|
|
Assert.Equal(1, EntriesCount(cc2.GetService<OpenAIRequestPolicies>()!));
|
|
}
|
|
|
|
private static int EntriesCount(OpenAIRequestPolicies policies)
|
|
{
|
|
var field = typeof(OpenAIRequestPolicies).GetField("_entries", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
|
|
var array = (Array?)field?.GetValue(policies);
|
|
return array?.Length ?? -1;
|
|
}
|
|
|
|
// -----------------------------------------------------------------------
|
|
// Direct unit tests for HostedAgentUserAgentPolicy's in-place upgrade behavior.
|
|
// These run the policy on a synthetic ClientPipeline (no hosting infrastructure)
|
|
// so the upgrade logic itself can be asserted in isolation.
|
|
// -----------------------------------------------------------------------
|
|
|
|
[Fact]
|
|
public async Task HostedAgentUserAgentPolicy_UpgradesBareAgentFrameworkSegment_InPlaceAsync()
|
|
{
|
|
// Arrange: an upstream per-call policy stamps the bare agent-framework-dotnet/{version}
|
|
// segment (matching what AgentFrameworkUserAgentPolicy would write in non-hosted code).
|
|
// Then HostedAgentUserAgentPolicy runs and must REPLACE that segment with the combined
|
|
// foundry-hosting/agent-framework-dotnet/{version} form, not append a duplicate.
|
|
using var handler = new InspectingHandler();
|
|
#pragma warning disable CA5399
|
|
using var httpClient = new HttpClient(handler);
|
|
#pragma warning restore CA5399
|
|
|
|
var pipeline = ClientPipeline.Create(
|
|
new ClientPipelineOptions { Transport = new HttpClientPipelineTransport(httpClient) },
|
|
perCallPolicies: [new SetUserAgentPolicy("agent-framework-dotnet/9.9.9"), HostedAgentUserAgentPolicy.Instance],
|
|
perTryPolicies: default,
|
|
beforeTransportPolicies: default);
|
|
|
|
// Act
|
|
var message = pipeline.CreateMessage();
|
|
message.Request.Method = "POST";
|
|
message.Request.Uri = new Uri("https://example.test/anything");
|
|
await pipeline.SendAsync(message);
|
|
|
|
// Assert: combined form is present; bare form is gone (no duplicate agent-framework segment).
|
|
Assert.NotNull(handler.LastUserAgent);
|
|
Assert.Contains("foundry-hosting/agent-framework-dotnet/", handler.LastUserAgent);
|
|
var ua = handler.LastUserAgent!;
|
|
var firstAgentFramework = ua.IndexOf("agent-framework-dotnet/", StringComparison.Ordinal);
|
|
Assert.True(firstAgentFramework >= 0, "Expected agent-framework-dotnet segment.");
|
|
var secondAgentFramework = ua.IndexOf("agent-framework-dotnet/", firstAgentFramework + 1, StringComparison.Ordinal);
|
|
Assert.Equal(-1, secondAgentFramework);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task HostedAgentUserAgentPolicy_AppendsCombined_WhenNoBareSegmentPresentAsync()
|
|
{
|
|
// Arrange: nothing upstream stamps the bare segment. Hosted policy should append the
|
|
// full combined segment to whatever User-Agent is on the wire.
|
|
using var handler = new InspectingHandler();
|
|
#pragma warning disable CA5399
|
|
using var httpClient = new HttpClient(handler);
|
|
#pragma warning restore CA5399
|
|
|
|
var pipeline = ClientPipeline.Create(
|
|
new ClientPipelineOptions { Transport = new HttpClientPipelineTransport(httpClient) },
|
|
perCallPolicies: [HostedAgentUserAgentPolicy.Instance],
|
|
perTryPolicies: default,
|
|
beforeTransportPolicies: default);
|
|
|
|
// Act
|
|
var message = pipeline.CreateMessage();
|
|
message.Request.Method = "POST";
|
|
message.Request.Uri = new Uri("https://example.test/anything");
|
|
await pipeline.SendAsync(message);
|
|
|
|
// Assert
|
|
Assert.NotNull(handler.LastUserAgent);
|
|
Assert.Contains("foundry-hosting/agent-framework-dotnet/", handler.LastUserAgent);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task HostedAgentUserAgentPolicy_IsIdempotent_WhenCombinedSegmentAlreadyPresentAsync()
|
|
{
|
|
// Arrange: upstream pre-populates the combined segment (simulating a retry or duplicate
|
|
// registration). Hosted policy must not re-append.
|
|
using var handler = new InspectingHandler();
|
|
#pragma warning disable CA5399
|
|
using var httpClient = new HttpClient(handler);
|
|
#pragma warning restore CA5399
|
|
|
|
var pipeline = ClientPipeline.Create(
|
|
new ClientPipelineOptions { Transport = new HttpClientPipelineTransport(httpClient) },
|
|
perCallPolicies: [new SetUserAgentPolicy("foundry-hosting/agent-framework-dotnet/9.9.9"), HostedAgentUserAgentPolicy.Instance],
|
|
perTryPolicies: default,
|
|
beforeTransportPolicies: default);
|
|
|
|
// Act
|
|
var message = pipeline.CreateMessage();
|
|
message.Request.Method = "POST";
|
|
message.Request.Uri = new Uri("https://example.test/anything");
|
|
await pipeline.SendAsync(message);
|
|
|
|
// Assert: exactly one occurrence of "foundry-hosting/agent-framework-dotnet/" segment.
|
|
Assert.NotNull(handler.LastUserAgent);
|
|
var first = handler.LastUserAgent!.IndexOf("foundry-hosting/agent-framework-dotnet/", StringComparison.Ordinal);
|
|
Assert.True(first >= 0);
|
|
var second = handler.LastUserAgent.IndexOf("foundry-hosting/agent-framework-dotnet/", first + 1, StringComparison.Ordinal);
|
|
Assert.Equal(-1, second);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task HostedAgentUserAgentPolicy_ReplacesDifferentVersionCombinedSegment_InPlaceAsync()
|
|
{
|
|
// Q-D regression: when the User-Agent already carries the COMBINED hosted form with a
|
|
// different version (e.g. an older registration or caller-supplied baseline), the policy
|
|
// must replace the entire combined span — not just the bare suffix — so we never emit
|
|
// the malformed `foundry-hosting/foundry-hosting/agent-framework-dotnet/...` shape.
|
|
using var handler = new InspectingHandler();
|
|
#pragma warning disable CA5399
|
|
using var httpClient = new HttpClient(handler);
|
|
#pragma warning restore CA5399
|
|
|
|
var pipeline = ClientPipeline.Create(
|
|
new ClientPipelineOptions { Transport = new HttpClientPipelineTransport(httpClient) },
|
|
perCallPolicies: [new SetUserAgentPolicy("foundry-hosting/agent-framework-dotnet/0.0.1 MEAI/10.5.1"), HostedAgentUserAgentPolicy.Instance],
|
|
perTryPolicies: default,
|
|
beforeTransportPolicies: default);
|
|
|
|
// Act
|
|
var message = pipeline.CreateMessage();
|
|
message.Request.Method = "POST";
|
|
message.Request.Uri = new Uri("https://example.test/anything");
|
|
await pipeline.SendAsync(message);
|
|
|
|
// Assert: no doubled foundry-hosting/ prefix.
|
|
Assert.NotNull(handler.LastUserAgent);
|
|
Assert.DoesNotContain("foundry-hosting/foundry-hosting/", handler.LastUserAgent, StringComparison.Ordinal);
|
|
|
|
// The combined segment must appear exactly once, and the trailing MEAI segment must be
|
|
// preserved in place (i.e. the policy only rewrote the combined span, not anything after it).
|
|
var firstCombined = handler.LastUserAgent!.IndexOf("foundry-hosting/agent-framework-dotnet/", StringComparison.Ordinal);
|
|
Assert.True(firstCombined >= 0);
|
|
var secondCombined = handler.LastUserAgent.IndexOf("foundry-hosting/agent-framework-dotnet/", firstCombined + 1, StringComparison.Ordinal);
|
|
Assert.Equal(-1, secondCombined);
|
|
Assert.Contains(" MEAI/10.5.1", handler.LastUserAgent, StringComparison.Ordinal);
|
|
|
|
// And the version that survives must be the runtime supplement value's version, not 0.0.1.
|
|
Assert.DoesNotContain("foundry-hosting/agent-framework-dotnet/0.0.1", handler.LastUserAgent, StringComparison.Ordinal);
|
|
}
|
|
|
|
private sealed class InspectingHandler : HttpClientHandler
|
|
{
|
|
public string? LastUserAgent { get; private set; }
|
|
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
{
|
|
this.LastUserAgent = request.Headers.TryGetValues("User-Agent", out var values)
|
|
? string.Join(",", values)
|
|
: null;
|
|
|
|
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
|
|
{
|
|
Content = new StringContent("{}", Encoding.UTF8, "application/json"),
|
|
RequestMessage = request,
|
|
});
|
|
}
|
|
}
|
|
|
|
private sealed class SetUserAgentPolicy : PipelinePolicy
|
|
{
|
|
private readonly string _value;
|
|
public SetUserAgentPolicy(string value) => this._value = value;
|
|
|
|
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
|
|
{
|
|
message.Request.Headers.Set("User-Agent", this._value);
|
|
ProcessNext(message, pipeline, currentIndex);
|
|
}
|
|
|
|
public override ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
|
|
{
|
|
message.Request.Headers.Set("User-Agent", this._value);
|
|
return ProcessNextAsync(message, pipeline, currentIndex);
|
|
}
|
|
}
|
|
|
|
private sealed class NoopHandler : HttpMessageHandler
|
|
{
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
=> Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
|
|
}
|
|
|
|
private sealed class RecordingHandler : HttpClientHandler
|
|
{
|
|
private readonly string _body;
|
|
public List<RecordedRequest> Requests { get; } = [];
|
|
|
|
public RecordingHandler(string body)
|
|
{
|
|
this._body = body;
|
|
}
|
|
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
{
|
|
string ua = request.Headers.TryGetValues("User-Agent", out var values)
|
|
? string.Join(",", values)
|
|
: "(none)";
|
|
this.Requests.Add(new RecordedRequest(request.RequestUri?.ToString() ?? "?", ua));
|
|
|
|
var resp = new HttpResponseMessage(HttpStatusCode.OK)
|
|
{
|
|
Content = new StringContent(this._body, Encoding.UTF8, "application/json"),
|
|
RequestMessage = request,
|
|
};
|
|
return Task.FromResult(resp);
|
|
}
|
|
}
|
|
|
|
private readonly record struct RecordedRequest(string Uri, string UserAgent);
|
|
}
|