Commit Graph

4 Commits

  • .NET: Issue 5662 (#5668)
    * Fix dangling function_call on approval response in Foundry hosting (#5662)
    
    Make the wire<->AF approval translation in Microsoft.Agents.AI.Foundry.Hosting lossless so the resume turn pairs function_call/function_call_output correctly.
    
    Root cause: InputConverter.ConvertMcpApprovalResponse rebuilt FunctionCallContent with CallId set to the FICC-composed AF request id (ficc_<callId>) and Name hardcoded to 'mcp_approval'. This (a) broke Azure Conversations pairing because the persisted function_call had CallId <callId> without prefix, and (b) made FICC unable to invoke the original tool by name on resume.
    
    Fix: ToolApprovalIdMap now records the original FunctionCallContent (CallId, Name, Arguments) keyed by wire id at outbound time. InputConverter reconstructs the original FCC on inbound, falling back to the legacy placeholder when no mapping exists.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Suppress orphan function_call items at the wire (#5662)
    
    Foundry-Hosting's OutputConverter was emitting FunctionCallContent as wire `function_call` items while dropping the paired FunctionResultContent. The result: every auto-invoked tool call left an orphan `function_call` in the response store. The next turn (chained via previous_response_id or via a workflow that yields after one turn under externalLoop) reloaded that history and submitted it to Azure Conversations, which rejected it with HTTP 400 `No tool output found for function call ...`.
    
    Function call/result pairs are entirely internal to the agent's tool-calling loop and have no place on the wire. Approval-required calls already surface separately via ToolApprovalRequestContent → mcp_approval_request, so dropping FCC is safe.
    
    FCC's message-close behavior is preserved so pre-tool text doesn't accidentally concatenate with post-tool text under the same MessageId. Existing OutputConverter tests asserting FCC wire emission are updated to assert suppression.
    
    Verified end-to-end against the declarative-workflow-menu external_loop bench: three-turn previous_response_id chain (menu → carbonara price → EXIT) now completes, where it previously failed at turn 2 with HTTP 400.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Fail fast when no approval mapping is recorded (#5662)
    
    The previous best-effort placeholder fallback in InputConverter.ConvertMcpApprovalResponse couldn't actually round-trip — it just delayed and obscured the failure as an HTTP 400 deep inside the agent loop. Throw InvalidOperationException with the wire id and a clear cause hint instead so the failure is local and actionable.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Trim narrative comments and exception message (#5662)
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Defer FunctionCallContent emission until matched FunctionResultContent (#5662)
    
    Replace blanket FCC suppression with deferred emission. FunctionCallContent
    is buffered (name + serialized arguments) keyed by CallId; the function_call
    and function_call_output wire items are only flushed once the matching
    FunctionResultContent arrives.
    
    - Auto-invoked FCC/FRC pairs surface as paired wire items so Azure's stored
      conversation has matched call+output and previous_response_id resume
      works (closes the orphan-function_call symptom from #5662).
    - Orphan FCCs (e.g. workflow paused at a checkpoint mid-tool-loop) are
      dropped so they never poison the response store.
    - Approval flows are unchanged: TARC still emits mcp_approval_request and
      the post-approval FRC has no buffered FCC to pair with so it is dropped;
      the approval round-trip handles its own pairing via mcp_approval_*.
    - Leaves the door open for future client-side function calling: that
      pattern would surface an FCC without an FRC, would need to opt out of
      buffering, but the wire shape is already correct.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Emit FunctionCallContent and FunctionResultContent directly (option B)
    
    Replace the deferred-emission/buffer-and-drop strategy with direct emission of both function_call and function_call_output wire items.
    
    Rationale: a lone FunctionCallContent in OutputConverter's input can mean two semantically different things, and only the caller knows which:
    
    - Auto-invoke (FICC response surface): always paired with a matching FRC; both halves should appear on the wire as historical record.
    
    - HITL / port-pause request (typed RequestPort<FunctionCallContent,...> or workflow synthesizing a request): a lone FCC IS the wire signal that the caller must resume by supplying a function_call_output.
    
    Buffering+dropping orphans silently swallows the second case. Emitting both directly is the only correct shape for OpenAI Responses semantics.
    
    The InputConverter already accepts function_call_output and mcp_approval_response on resume, so the round-trip works for both kinds.
    
    The approval-flow round-trip fixes (ToolApprovalIdMap rich ApprovalEntry, fail-fast on missing mapping in ConvertMcpApprovalResponse) remain intact.
    
    Tests: updated 7 OutputConverter tests + 1 OutputConverterWorkflow test that asserted the old buffer/drop semantics; all 227 tests pass.
    
    Refs #5662
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Address PR #5668 review feedback on TryLoadMap
    
    Stop swallowing JsonException in ToolApprovalIdMap.TryLoadMap. The catch block recovered to an empty map and a stale comment claimed the caller would gracefully degrade via a 'wire-id fallback path' — but that path no longer exists: InputConverter.ConvertMcpApprovalResponse fails fast when no entry is found.
    
    Letting the JsonException propagate produces an error message that points at the actual cause (a state-bag format incompatibility), instead of converting it into a confusing 'no approval mapping recorded' InvalidOperationException one stack frame later.
    
    Refs #5662, PR #5668
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Address PR #5668 review feedback round 2
    
    - OutputConverter FRC: emit string results as raw text (no JSON-quoting),
      matching the wire contract for function_call_output.output.
    - OutputConverter FCC: validate non-empty CallId before closing the in-flight
      text message, so a skipped FCC no longer breaks output-item boundaries.
    - ToolApprovalIdMap.Record: take pre-serialized arguments JSON (string) and
      primitive callId/name. Drops [RequiresUnreferencedCode]/[RequiresDynamicCode]
      so trim/AOT warnings stop propagating to call sites.
    - ToolApprovalIdMap.Record: no-op when callId or name is empty.
    - Tests: dedup duplicate ConvertItemsToMessages_McpApprovalResponse no-mapping
      test; add coverage for empty-CallId boundary, raw-string FRC payload, and
      Record empty-key no-op.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    ---------
    
    Co-authored-by: alliscode <bentho@microsoft.com>
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
  • .NET: Bump MEAI to 10.5.1 and add Foundry per-call x-client header support (#5652)
    * Bump MEAI to 10.5.1 and add per-call x-client header support
    
    Replaces the brittle UserAgentResponsesClient subclass with a clean
    per-call x-client-* header pipeline built on the new Microsoft.Extensions.AI
    10.5.1 OpenAIRequestPolicies hook.
    
    Public surface (Microsoft.Agents.AI.Foundry, [Experimental(MAAI001)]):
    * chatOptions.WithClientHeader(name, value) and .WithClientHeaders(IEnumerable)
      validate the x-client- prefix (case-insensitive), apply all-or-nothing on
      bulk, and throw InvalidOperationException on foreign-typed slot collision
    * myAgent.AsBuilder().UseClientHeaders().Build() opts a customer-built agent
      into the pipeline; idempotent via agent.GetService<ClientHeadersAgent>()
    * Foundry-built agents (FoundryAgent.Create*) pre-wire automatically
    
    Internals:
    * ClientHeadersAgent decorator snapshots the dict at scope-push time so
      concurrent runs sharing a ChatOptions reference do not leak headers
    * ClientHeadersScope is an AsyncLocal<IReadOnlyDictionary<string,string>?>
      with LIFO push/dispose semantics
    * ClientHeadersPolicy singleton stamps headers via Headers.Set so per-call
      values overwrite any same-name header from earlier policies and so
      duplicate registration is value-stable
    * OpenAIRequestPoliciesReflection dedups against MEAI's private _entries
      field and falls back to AddPolicy on any reflection failure; a CI test
      asserts the field shape on every MEAI bump
    
    Hosting cleanup:
    * Deleted UserAgentResponsesClient and its dummy throwing pipeline
    * HostedAgentUserAgentPolicy is now registered via OpenAIRequestPolicies
      in FoundryHostingExtensions.TryApplyUserAgent
    
    Tests:
    * 19 new unit tests in ClientHeadersExtensionsTests.cs covering validation,
      AsyncLocal isolation, snapshot semantics, end-to-end wire stamping, and
      shared-chat-client dedup
    * Updated OpenTelemetryAgentTests for MEAI 10.5.1 changes to web_search
      serialization and the reduced tool definition payload when sensitive
      data capture is disabled
    
    Microsoft.Extensions.Compliance.Abstractions stays at 10.5.0 because no
    10.5.1 release exists on nuget.org.
    
    * Address PR review: pre-wire AsAIAgent path and dedup TryApplyUserAgent
    
    * FoundryAgent: extract WireClientHeaders helper and call it from the
      internal (AIProjectClient, ChatClientAgent) constructor used by
      AzureAIProjectChatClientExtensions.AsAIAgent so those Foundry-built
      agents also pre-wire the x-client header pipeline.
    * Foundry.Hosting TryApplyUserAgent: dedup HostedAgentUserAgentPolicy
      registration per OpenAIRequestPolicies instance via
      ConditionalWeakTable so per-request resolution does not grow the
      policy list unboundedly on singleton agents.
    
    * Add tests covering AsAIAgent pre-wire and TryApplyUserAgent dedup
    
    Backs the PR review fixes from a4c8f91 with regression tests:
    * ClientHeadersExtensionsTests: AsAIAgent_FoundryAgent_HasPreWiredClientHeadersAgent
      asserts the FoundryAgent built via AzureAIProjectChatClientExtensions.AsAIAgent
      contains a ClientHeadersAgent in its delegating chain (catches future
      regressions of the bypass).
    * ClientHeadersExtensionsTests: FoundryAgent_PublicConstructor_HasPreWiredClientHeadersAgent
      covers the public constructor path the same way.
    * ClientHeadersExtensionsTests: UseClientHeaders_RepeatedRegistrations_OnSameChatClient_OnlyRegistersOnce
      invokes UseClientHeaders 25 times on a shared chat client and asserts via
      reflection that OpenAIRequestPolicies._entries length is exactly 1.
    * HostedTryApplyUserAgentDedupTests: two tests asserting
      FoundryHostingExtensions.TryApplyUserAgent stays at one entry per
      OpenAIRequestPolicies instance after 50 calls on the same agent and across
      distinct agents on different chat clients.
    
    * Move tests next to their SUT
    
    Removes the dedicated HostedTryApplyUserAgentDedupTests.cs test class.
    Tests are co-located with the SUT they exercise:
    
    * FoundryAgentTests.cs gains the Constructor_PreWiresClientHeadersAgent
      and Constructor_FromAsAIAgentExtension_PreWiresClientHeadersAgent
      cases, since FoundryAgent is the SUT for the pre-wire behavior.
    * HostedOutboundUserAgentTests.cs gains the two TryApplyUserAgent dedup
      cases, since FoundryHostingExtensions.TryApplyUserAgent is the SUT
      it already covers.
    * ClientHeadersExtensionsTests.cs keeps only the
      UseClientHeaders_RepeatedRegistrations_OnSameChatClient_OnlyRegistersOnce
      case, which exercises the public ClientHeadersExtensions surface.
    
    * Remove redundant WithCancellation on inner streaming call
    
    ct is already passed to InnerAgent.RunStreamingAsync, so
    .WithCancellation(ct) on the resulting IAsyncEnumerable is a no-op.
    Caught by Sergey on PR review.
    
    * Address PR review: surface downstream MEAI experimental ID
    
    * Add AIOpenAIRequestPolicies = MEAIExperiments alias to
      DiagnosticIds.Experiments (matches the existing AIResponseContinuations,
      AIMcpServers, AIFunctionApprovals pattern).
    * Mark public ClientHeadersExtensions with [Experimental(AIOpenAIRequestPolicies)]
      instead of AgentsAIExperiments. Consumers now see the MEAI001 warning,
      surfacing the dependency on MEAI's experimental OpenAIRequestPolicies hook.
    * Mark internal OpenAIRequestPoliciesReflection with the same alias to
      suppress warnings at the source rather than via project-wide NoWarn.
    * Remove MEAI001 from Foundry csproj NoWarn (kept on Foundry.Hosting where
      pre-PR usages remain).
    * Clarify ClientHeadersScope XML doc: AsyncLocal flows values forward but
      does NOT auto-restore on method return; explicit using/Dispose is what
      gives stack-style LIFO semantics.
  • .NET: Hosting updates to declarative workflows (#5589)
    * Make DeclarativeWorkflowExecutor ChatProtocol-compatible for AsAIAgent hosting
    
    Extends the existing DeclarativeWorkflowExecutor<TInput> root executor with
    additional ChatProtocol-compatible input routes (string, ChatMessage,
    IEnumerable<ChatMessage>, ChatMessage[], TurnToken) so that workflows built
    via DeclarativeWorkflowBuilder.Build<TInput>(...) work both for direct
    invocation and when hosted via Workflow.AsAIAgent(...).
    
    - Each input message advances the declarative graph immediately; the
      TurnToken that the host sends after the message batch is treated as a
      no-op since the message has already been processed.
    - Conversation id resolution now prefers persisted workflow system state,
      then DeclarativeWorkflowOptions.ConversationId, then a newly created
      conversation. This makes multi-turn invocations reuse the prior
      conversation rather than creating a fresh one each turn.
    - The separate DeclarativeChatProtocolStartExecutor and
      DeclarativeWorkflowBuilder.BuildChatProtocol overloads introduced
      earlier are removed; callers continue to use Build<TInput>(...).
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * fix: use DeclarativeWorkflowContext when reading workflow conversation id
    
    GetWorkflowConversation() requires a DeclarativeWorkflowContext (it calls ReadState which dynamic-casts via the DeclarativeContext helper). The chat-protocol auxiliary handlers receive a BoundWorkflowContext, so calling the extension on the raw IWorkflowContext throws `Invalid workflow context: BoundWorkflowContext`. Use the wrapped declarativeContext that we already constructed.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * fix: surface ExecutorFailedEvent as ErrorContent in AsAIAgent response
    
    WorkflowSession.InvokeStageAsync only converted WorkflowErrorEvent into an ErrorContent payload. ExecutorFailedEvent fell through to the default branch which emits an empty AgentResponseUpdate carrying the event in RawRepresentation. OutputConverter then mapped that to a workflow_action item with status=failed and dropped the exception entirely, so callers got status=completed and error=null even when an executor threw.
    
    - WorkflowSession.cs: add ExecutorFailedEvent case mirroring WorkflowErrorEvent. Honors _includeExceptionDetails.
    
    - OutputConverter.cs: when an update carries both a WorkflowEvent in RawRepresentation and non-empty Contents, fall through to content processing so the unwrapped error (or any future content payload from a workflow event) is actually emitted.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * improve: walk inner exceptions when surfacing ExecutorFailedEvent
    
    DeclarativeActionExecutor wraps inner exceptions in DeclarativeActionException with a generic `Unhandled workflow failure` message, hiding the real cause. Walk InnerException so the response shows the full chain (e.g. the underlying HTTP 400 / auth error).
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Surface declarative SendActivity output as chat content
    
    SendActivityExecutor now emits AgentResponseEvent in addition to
    MessageActivityEvent so chat protocols (e.g. AsAIAgent) receive the
    formatted activity text. The existing MessageActivityEvent is preserved
    for DevUI/observability.
    
    Also extend WorkflowSession.WorkflowOutputEvent handling to accept
    AgentResponse payloads, mapping them to their constituent ChatMessages.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Persist hosted-agent sessions to disk; fix System.LastMessageText
    
    Adds FileSystemAgentSessionStore that writes the serialized AgentSession JSON
    
    (which already embeds the workflow's in-memory checkpoint manager) to a per-
    
    conversation file under /.checkpoints when running in a Foundry hosted env
    
    or {cwd}/.checkpoints locally. Mirrors the python foundry_hosting._responses
    
    FileCheckpointStorage pattern so multi-turn workflow state survives process
    
    restarts without requiring callers to wire up storage themselves.
    
    AddFoundryResponses now defaults to FileSystemAgentSessionStore.CreateDefault()
    
    instead of InMemoryAgentSessionStore; callers can still override via DI.
    
    Also fixes {System.LastMessageText} resolving empty: DeclarativeWorkflowExecutor
    
    .AdvanceAsync was passing the message rehydrated from CreateMessageAsync to
    
    SetLastMessageAsync, but ResponseItem -> ChatMessage round-trip drops the .Text
    
    extension content. Use the original input ChatMessage (which still has the
    
    user-supplied text) and copy the server-assigned MessageId across when present.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Close multi-modal input parity gaps with python foundry_hosting
    
    InputConverter now mirrors the python _responses.py content handling:
    
    - ComputerScreenshotContent maps to UriContent/HostedFileContent (was dropped).
    
    - Plain TextContent and SummaryTextContent map to MEAI TextContent.
    
    - MessageContentReasoningTextContent maps to MEAI TextReasoningContent.
    
    - input_file with text/* file_data data URIs is decoded inline into
    
      TextContent with a [File: name] prefix, matching python _convert_file_data
    
      so {System.LastMessageText} surfaces the file body. Non-text data URIs and
    
      hosted/url file references preserve filename as AdditionalProperties.
    
    Image/file extraction logic is extracted into shared AppendImageContent and
    
    AppendFileContent helpers used by both the fresh-input and history-replay
    
    switches. Existing 37 InputConverter tests still pass.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Foundry hosting: round-trip tool-approval (HITL) content as mcp_approval_request/response
    
    Closes the gap where Microsoft.Agents.AI.Foundry.Hosting silently dropped
    MEAI ToolApprovalRequestContent/ToolApprovalResponseContent in both
    directions. We now serialize them onto the wire as the standard Responses
    API mcp_approval_request/mcp_approval_response items with
    server_label='agent_framework', and parse the symmetric inbound shapes
    back into MEAI content.
    
    Wire format:
    - The Responses API only standardizes mcp_approval_* as the approval
      primitive. We declare AF as a virtual MCP server via the server_label
      field, which is honest for AF's server-side tool-call holding pattern.
    - The SDK enforces a strict {prefix}_{50hex} wire-id format, so we hash
      the AF RequestId and persist a wireId<->afRequestId mapping in
      AgentSession.StateBag so a later mcp_approval_response can be matched
      back to the originating workflow request.
    
    Coexists with the existing ConsentAwareMcpClientAIFunction flow
    (AgentFrameworkResponseHandler.cs) which emits mcp_approval_request from
    a side-channel, not via OutputConverter's content switch.
    
    Known follow-up: python (foundry_hosting/_responses.py) has the same
    output-side gap (ToolApprovalRequestContent emission). Out of scope here.
    
    Tests: +9 unit tests covering both fresh-input and history-replay shapes,
    StateBag mapping resolution, and the non-FunctionCallContent skip path.
    Existing 108 converter tests still pass; full suite 370/370.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Address PR review feedback for hosted-declarative-dotnet
    
    FileSystemAgentSessionStore reliability/scoping:
    
    - Bound Sanitize() stackalloc at 256 chars, fall back to ArrayPool for longer ids so a long conversationId can no longer crash the hosting process with StackOverflowException.
    
    - Use a Guid-suffixed temp file (\{path}.{guid}.tmp\) so concurrent SaveSessionAsync calls on the same conversation can no longer race on the same temp file. Best-effort temp cleanup on failure.
    
    - Bucket session files by agent.Name when set so two keyed agents that happen to share a conversationId no longer overwrite each other's persisted state. Single-agent / unnamed-agent cases keep the original flat layout (Python parity).
    
    DeclarativeWorkflowExecutor chat-protocol routing:
    
    - ConfigureChatProtocolRoutes uses IsAssignableFrom rather than exact type equality so a broader TInput (object, base interfaces) does not have its inherited inputTransform shadowed by handlers we register here.
    
    - HandleChatMessagesAsync / HandleChatMessageArrayAsync now advance through every message in the batch instead of keeping only the trailing one, so multi-message turns and replayed history are no longer silently truncated. AdvanceAsync gains a finalizeTurn flag so only the last message in the batch sends the result.
    
    Tests:
    
    - New FileSystemAgentSessionStoreTests covering constructor, fresh-session fallback for missing/empty files, root-directory creation, save/get round-trip, agent-Name scoping isolation, long conversationId, invalid-character sanitization, and concurrent-save behavior.
    
    - New InputConverterTests covering AppendFileContent: text/* data URI decode (with and without filename prefix), non-text data URI passthrough, malformed data URI fallback, and filename propagation onto UriContent / HostedFileContent.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Add tests for remaining PR review feedback (C2, D1, E1)
    
    C2: InputConverter — add 9 tests covering SDK content types that previously
    had no coverage:
      - SdkTextContent → TextContent (input + output paths)
      - SummaryTextContent → TextContent (input + output paths)
      - MessageContentReasoningTextContent → TextReasoningContent (input + output)
      - ComputerScreenshotContent (HTTP URL → UriContent, data: URI → DataContent,
        output path → UriContent)
    
    D1: OutputConverter — add 2 tests for the WorkflowEvent + Contents fall-through:
      - WorkflowEvent in RawRepresentation with text Contents must flow through
        the content-processing path (text-delta event emitted).
      - WorkflowEvent + ErrorContent must produce a failed event rather than be
        swallowed by the workflow branch.
    
    E1: SendActivityExecutor — extend CaptureActivityAsync to assert that the
    executor emits an AgentResponseEvent carrying the activity text with the
    correct ExecutorId and ChatRole.Assistant role.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Defense-in-depth: neutralize dot-segments in Sanitize and cap TryDecodeTextDataUri input size
    
    Addresses claude-opus-4.6 security review on PR #5589:
    
    - FileSystemAgentSessionStore.Sanitize now replaces all-dot segments
      (., .., ...) with underscores so a developer-controlled agent.Name
      cannot escape the root directory on Linux (where Path.GetInvalidFileNameChars
      only contains NUL and '/').
    
    - InputConverter.TryDecodeTextDataUri rejects encoded payloads larger than
      16 MiB before calling Convert.FromBase64String, preventing a single
      oversized data URI from triggering a multi-megabyte allocation.
    
    - Adds unit tests covering both fixes.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Fix Linux-only failure in SaveSessionAsync_SanitizesInvalidPathCharactersAsync
    
    '?' is in Path.GetInvalidFileNameChars only on Windows, not on Linux/macOS,
    so the test failed on Ubuntu in CI. Use Path.GetInvalidFileNameChars()[0]
    (skipping NUL) to pick a guaranteed-invalid character for the running OS,
    and assert the result no longer contains it.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Address claude-opus-4.6 security/reliability review feedback
    
    WorkflowSession.cs:
    - ExecutorFailedEvent handler no longer leaks the internal executor ID
      in error messages. Mirror the WorkflowErrorEvent pattern: surface the
      exception's Message when _includeExceptionDetails is true, fall back
      to the generic 'An error occurred while executing the workflow.' otherwise.
      This also resolves the failing WorkflowHostSmokeTests assertions.
    
    FileSystemAgentSessionStore.cs:
    - GetSessionPath no longer has a write side effect. Directory.CreateDirectory
      for the per-agent bucket is now performed only on the SaveSessionAsync
      path, so a read miss on GetSessionAsync no longer leaves an empty
      directory on disk.
    - Adds GetSessionAsync_NoExistingFile_DoesNotCreateAgentDirectoryAsync
      to lock in the no-side-effect-on-read contract.
    
    OutputConverterTests.cs:
    - Strengthen ConvertUpdatesToEventsAsync_ToolApprovalRequest_NonFunctionToolCall_SkippedAsync
      to assert exactly one event (the terminal ResponseCompletedEvent) so a
      spurious output-item-added/-done leak would now fail the test.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Address PR review: clean up comments and rename TryParseArguments
    
    - Remove Python-codebase references from C# XML docs and inline comments.
    - Drop fix-history comments referring to previously-resolved issues.
    - Drop `Defense-in-depth:` prefixes; keep the concrete `what & why`.
    - Drop `previously we kept only the trailing message` comment in
      DeclarativeWorkflowExecutor; just describe current loop behavior.
    - Rename InputConverter.TryParseArguments to ParseFunctionArgumentsObject
      to make the intent obvious at the call site.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Address PR review: collision-free Sanitize, MAF-style refactors
    
    - FileSystemAgentSessionStore.Sanitize now percent-encodes invalid chars
      (and `%` itself) instead of replacing them with `_`, eliminating
      collisions like `foo/bar` vs `foo_bar` mapping to the same bucket.
      All-dot segments encode every dot so Windows trailing-dot trimming
      cannot reintroduce a navigable name.
    - AddFoundryResponses XML doc updated to accurately describe the default
      store root (/.checkpoints when hosted, {cwd}/.checkpoints locally).
    - DeclarativeWorkflowExecutor.ConfigureChatProtocolRoutes now uses exact
      type equality instead of IsAssignableFrom so a broad TInput (e.g.
      object) does not skip registering IEnumerable<ChatMessage>, which
      ChatProtocolExtensions.IsChatProtocol requires verbatim.
    - SendActivityExecutor uses context.YieldOutputAsync(response) instead
      of manually constructing AgentResponseEvent, so the activity will
      participate in any future OutputFilter coverage.
    - WorkflowSession handles AgentResponseEvent in its own switch case,
      avoiding the second typecheck against output.Data.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * fix(workflows): bridge declarative HITL through Foundry hosting via IExternalRequestEnvelope
    
    Introduce a new public interface IExternalRequestEnvelope in
    Microsoft.Agents.AI.Workflows that lets the runtime peek through a
    declarative-layer envelope without taking a circular reference back into
    the declarative package. ExternalInputRequest (declarative) implements
    it; ExternalInputResponse is constructed via the request's CreateResponse
    factory. WorkflowSession unwraps inner AIContent on the request side and
    rewraps the client's ChatMessage reply into an ExternalInputResponse on
    the response side. PortableValue cannot deserialize directly into an
    interface, so TryGetRequestEnvelope resolves the concrete type via
    RequestPortInfo.RequestType (TypeId -> Type.GetType) before casting.
    
    Public WorkflowHarness contract preserved: InvokeFunctionToolExecutor
    and WorkflowActionVisitor are unchanged from upstream, so public
    InvokeToolWorkflowTest scenarios continue to drive
    ExternalInputRequest / ExternalInputResponse directly through the
    harness.
    
    AgentFrameworkResponseHandler: skip prior conversation history replay
    when an existing session is being resumed (workflow checkpoint already
    holds the prior messages).
    
    WorkflowSession: when includeExceptionDetails is opted in, also unwrap
    DeclarativeActionException so HITL failures are debuggable.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    ---------
    
    Co-authored-by: alliscode <bentho@microsoft.com>
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
  • .NET: Add dedicated Foundry.Hosting UnitTest project (#5592)
    * Foundry.Hosting.UnitTests: extract project from Foundry.UnitTests
    
    Move all Hosting/* tests, three toolbox TestData JSONs, and the FakeAuthenticationTokenProvider/HttpHandlerAssert/TestDataUtil helpers (trimmed to toolbox getters) into a new Microsoft.Agents.AI.Foundry.Hosting.UnitTests project. Add it to the slnx and grant the new assembly InternalsVisibleTo from Microsoft.Agents.AI.Foundry and Microsoft.Agents.AI.Foundry.Hosting.
    
    * Foundry.Hosting.UnitTests: align namespaces to assembly name
    
    Rename namespaces from Microsoft.Agents.AI.Foundry.UnitTests(.Hosting) to Microsoft.Agents.AI.Foundry.Hosting.UnitTests across all moved tests, the duplicated helpers, and the trimmed TestDataUtil. Also fixes the prior namespace inconsistency in FoundryToolboxTests.
    
    * Foundry.Hosting.UnitTests: split WorkflowIntegrationTests by SUT
    
    Replace the WorkflowIntegrationTests file (an IT-named file inside a UT project) with two SUT-focused files plus a shared test-doubles file:
    
    - AgentFrameworkResponseHandlerWorkflowTests.cs - the 5 handler-driven tests that exercise AgentFrameworkResponseHandler with a real workflow agent.
    - OutputConverterWorkflowTests.cs - the 5 OutputConverter tests driven by hand-crafted update sequences mirroring real workflow patterns.
    - WorkflowTestAgents.cs - StreamingTextAgent and ThrowingStreamingAgent extracted as internal types used by both files.
    
    * Foundry.UnitTests: trim Hosting-related conditionals and dead testdata
    
    Now that Hosting tests live in their own project:
    - drop the Compile Remove guard for the Hosting subfolder,
    - drop the .NETCoreApp-only PackageReferences (Azure.AI.AgentServer.Responses, Microsoft.AspNetCore.TestHost, OpenTelemetry, OpenTelemetry.Exporter.InMemory),
    - drop the conditional ProjectReference to Microsoft.Agents.AI.Foundry.Hosting,
    - delete the three Toolbox JSON files and the matching Toolbox getters in TestDataUtil.
    
    * Foundry.Hosting.UnitTests: drop redundant 'using Microsoft.Agents.AI.Foundry.Hosting'
    
    The new project namespace is Microsoft.Agents.AI.Foundry.Hosting.UnitTests, which already brings the parent Microsoft.Agents.AI.Foundry.Hosting namespace into scope. The explicit using statement is therefore redundant (IDE0005). Caught by 'dotnet format --verify-no-changes' running on Linux against the .NET 10 SDK.
    
    * Foundry.Hosting: drop InternalsVisibleTo to Foundry.UnitTests
    
    The non-hosting Foundry.UnitTests project no longer holds any Hosting tests after the split, so it doesn't need access to internal types in Microsoft.Agents.AI.Foundry.Hosting. Only Microsoft.Agents.AI.Foundry.Hosting.UnitTests needs it.
    
    * Foundry.Hosting: rename DelegatingResponsesClient to UserAgentResponsesClient
    
    Address westey-m's review feedback on PR #5453: `Delegating*` is conventionally reserved for inheritable base classes (mirroring `DelegatingHandler`) where consumers override one or two members. This polyfill is sealed and only injects the User-Agent supplement, so the new name reflects its actual purpose.
    
    Renamed via `git mv` to preserve history:
    * `src/Microsoft.Agents.AI.Foundry.Hosting/DelegatingResponsesClient.cs` to `UserAgentResponsesClient.cs`
    * `tests/Microsoft.Agents.AI.Foundry.Hosting.UnitTests/DelegatingResponsesClientTests.cs` to `UserAgentResponsesClientTests.cs`
    
    Class, constructor, and all references updated across:
    * `src/.../UserAgentResponsesClient.cs` (class + constructor + internal log message)
    * `src/.../ServiceCollectionExtensions.cs` (cref + type check + instantiation)
    * `src/.../HostedAgentUserAgentPolicy.cs` (cref)
    * `tests/Foundry.UnitTests/RequestOptionsExtensionsTests.cs` (comment)
    * `tests/Foundry.Hosting.UnitTests/UserAgentResponsesClientTests.cs` (class + cref + instantiations)